I have been attempting to code a windows form application that interacts with facebook to retrieve the access token that has permissions to get some of the user's information. I have been trying to get the birthday of myself using the following code but it keeps giving me the 400 bad request error. Basically after running this code, and logging in at the authentication it is suppose to show a messagebox containing the user's birthday. In this case, I am using my own user id in the api.GET method. It seems to be the access token issue as when I don't pass in any tokens, i can view public available information such as id using the same code but I print out the access token to check and it seems to be alright. Any help would be much appreciated. First time posting here
public partial class AccessTokenRetrieval : Form
{
private string accessToken=null;
public AccessTokenRetrieval()
{
InitializeComponent();
}
private void accessTokenButton_Click(object sender, EventArgs e)
{
string getAccessTokenURL = #"https://graph.facebook.com/oauth/authorize?client_id=223055627757352&redirect_uri=http://www.facebook.com/connect/login_success.html&type=user_agent&display=popup&grant_type=client_credentials&scope=user_photos,offline_access";
getAccessTokenWebBrowser.Navigate(getAccessTokenURL);
}
private void getAccessTokenWebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string successUrl = #"http://www.facebook.com/connect/login_success.html";
string urlContainingUserAuthKey = e.Url.ToString();
MessageBox.Show(urlContainingUserAuthKey);
int searchInt = urlContainingUserAuthKey.IndexOf(successUrl);
MessageBox.Show(searchInt.ToString());
if (urlContainingUserAuthKey.IndexOf(successUrl) == -1)
{
string accessTokenString;
accessTokenString = Regex.Match(urlContainingUserAuthKey, "access_token=.*&").ToString();
this.accessToken = accessTokenString.Substring(13, accessTokenString.Length - 14);
//100001067570373
//MessageBox.Show(accessToken);
accessTokenTextBox.Text = this.accessToken;
Facebook.FacebookAPI api = new Facebook.FacebookAPI(this.accessToken);
JSONObject me = api.Get("/100001067570373");
MessageBox.Show(me.Dictionary["user_birthday"].String);
}
}
#
I would request you to try http://facebooksdk.codeplex.com and checkout the samples folder.
It includes sample for WinForms authentication and also making various request to Facebook.
Here are other useful links that I would recommend you to read.
http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-first-Facebook-Application.aspx
http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx
Related
Ok. So this question might be a bit stupid but as I've searched and searched and haven't found a working solution I thought I might ask here.
I've put up a simple PHP page that gets 2 parameters from the url myusername and mypassword. Then gets 3 int values from a database according to the username and password given.
(tested it By typing the url in with the parameters and the PHP script itself works. Even made it to echo the 3 integers on the page to make sure)
Now to the problematic part. I'm using Visual Studio 2013 and making an Universal App for Windows 8.1. And I just can't seem to get the httpClient to get me any data from there. Through browsing the forums I haven't been able to find anything that works. Couldn't have tested all either as most use GetResponse() which doesn't work in VS 2013. As I'm fairly new to the C# coding it could be as simple as to a little mistake in the dozens of tests I've done.
Made a login screen with 2 text fields. And I can build the url in form of "www.something.com/something/somephp?myusername=UserNameGiven&mypassword=PasswordGiven"
If anyone could give a simple solution on how I might be able to get the results from the page that address opens (only shows the 3 integers through echo... can remove those too if those arent required for the C# code to work. String format would probably be ideal if not too much to ask...
Ok made a new GetScores async method for the code you gave SnyderCoder. Throwing that Task on login button would have required coding beyond my knowhow for the moment atleast.
Still Results.Text field remains at the default status and shows no change.
Changed the LoginButton back to async without task.
the state of my code from the c# is atm is
private async void LoginButton_Click(object sender, RoutedEventArgs e)
{
string UserName, Password;
UserName = UserNameFeedField.Text.ToString();
Password = PasswordFeedField.Text.ToString();
string url = "something.com/something/GetScores.php?myusername=" + UserName + "&mypassword=" + Password;
URL.Text = url;
// GetScores(url);
using (Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient())
{
string contentOFPage = await client.GetStringAsync(new Uri(url));
Results.Text = contentOFPage;
}
}
incase it matters here is the PHP code portion
<?php
$host="db_host"; // Host name
$username="db_user"; // Mysql username
$password="db_pswd"; // Mysql password
$db_name="db_name"; // Database name
$tbl_name="db_table"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_GET["myusername"];
$mypassword=$_GET["mypassword"];
// To protect MySQL injection (more detail about MySQL injection )
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT field1 as LowB, field2 as LongB, field3 as Bs FROM $tbl_name WHERE UserID='$myusername' and UserPSWD='$mypassword'";
$result=mysql_query($sql);
// this part only shows the variables gotten from the query and echoes those on the page
// was only made to test that the PHP works.
while ($row = mysql_fetch_assoc($result)) {
echo ($row["LowB"] . " " . $row["LongB"] . " " . $row["Bs"]);
}
?>
First a async method always needs to return a task. For the rest:
private async void LoginButton_Click(object sender, RoutedEventArgs e)
{
string UserName = UserNameFeedField.Text.ToString();
string Password = PasswordFeedField.Text.ToString();
string url = "www.something.com/something/some.php?myusername=" + UserName + "&mypassword=" + Password;
using (Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient())
{
string contentOfPage = await client.GetStringAsync(new Uri(url));
//Do something with the contentOfPage
}
}
I have some code that uses Google Apps as an Open ID provider to authenticate to my web application that is based on the example https://developers.google.com/google-apps/marketplace/tutorial_dotnet.
It all works as expected. However, when redirected to the Google Login screen, the 'Stay Signed In' checkbox is selected by default. I have found that if I manually add &rm=false to then end of the URL, the checkbox is unselected, which I believe is a more secure default option.
My question is, how can I pass &rm=false in my code. I've looked at AddCallbackArguments but this doesn't seem to be the way to do it.
Code is
private static readonly HostMetaDiscoveryService GoogleAppsDiscovery = new HostMetaDiscoveryService
{
UseGoogleHostedHostMeta = true,
};
private static readonly OpenIdRelyingParty relyingParty;
static login()
{
relyingParty = new OpenIdRelyingParty();
relyingParty.DiscoveryServices.Clear();
relyingParty.DiscoveryServices.Insert(0, GoogleAppsDiscovery);
}
protected void buLogin_Click(object sender, EventArgs e)
{
IAuthenticationRequest request = relyingParty.CreateRequest("mydomain");
request.RedirectToProvider();
}
I have tried to find answers on following questions for at least one hour but with no success.
I have WPF project (C#) and I have webBrowser control to navigate to my Facebook page http://www.facebook.com/TennisHelper and I want to do next few things:
I want to avoid login by creating user settings in my application which will contain email and password, but I don't know how to do that with C# Facebook SDK,
I want to make able for my user to post textual posts on that page via textBox control,
I want to make able for my user to post photos from his computer directly to that page, but with not creating new albums. Just to post image on page wall.
I was searching Google for all those problems but with no success
Let me know actually what is your requirement.I think your first requirement is to add a facebook login(or register with facebook page) button in your Website login page.
step1:You need to register a new facebook application on facebook.
step 2:install facebook c# sdk .You can either download the zip file manually or install it using nuget.I recommend the second option.I am using c# sdk 5.4.1 What is nuget? How to install a package using nuget?
step 3:Now you can add name space facebook to the page
step 4:Insert a login button(simply a button with text login) in login page(say login.aspx).Let it be button1
step 5:On click button redire to another page (let login1.aspx)
here is a sample code for login 1
using Facebook;//
FacebookOAuthClient fb = new FacebookOAuthClient();
UriBuilder red = new UriBuilder("www.example.com/Login1.aspx");
protected void Page_Load(object sender, EventArgs e)
{
string appid = "{your app id}";
string appsecret = "{your app secret}";
string permissions = "publish_stream";
if(Request.QueryString["code"] == null)
{
try
{
Response.Redirect("https://www.facebook.com/dialog/oauth?client_id=" + appid + "&redirect_uri=" + red.Uri.ToString() + "&scope=" + permissions +"&state=djfjfdjj");
}
catch (Exception b)
{
Label1.Text = b.ToString();
}
}
else
{
try
{
FacebookOAuthClient cl = new FacebookOAuthClient();
cl.RedirectUri = red.Uri;
cl.AppId = appid;
cl.AppSecret = appsecret;
dynamic result = cl.ExchangeCodeForAccessToken(Request.QueryString["code"]);
Label1.Text = Convert.ToString(result);
if (result["access_token"] != null)
{
Session["access_token"] = result["access_token"].ToString();//Now you have access token
Response.Redirect("Welcome.aspx");//replace welcome.aspx
}
else
{
Label1.Text = "Unable to authenticate\n Please try again later";
}
}
catch(Exception b)
{
Label1.Text = b.ToString();
}
}
}
Now you have access token saved in session.
for getting basic information of the client
dynamic me=fb.Get("\me");
it in cludes first name, last name ,email address,location,image url etc. of the current user.Now you can use this e-mail or name to verify your user or register new user etc.(its up to you ).
posting on that page is possible but diffiult How can I use the Facebook C# SDK to post on Facebook Pages
You should register an application on Facebook in order to use Facebook log in.navigate to
http://developers.facebook.com
create an appllication.You will get an application id and application secret.Use it as appid,appsecret
I want to create a Facebook IFRAME applicaton with asp.net. I just want to know should I need to host the application some where over internet? If yes, how could I test my application on localhost?
Update:
I just want a simple app for displaying a user name with "Hello." Can anyone show me the code for that with the complete web.config configuration?
I'm trying this code
using facebook.web;
namespace TestFbApplication
{
public partial class _Default:facebook.web.CanvasFBMLBasePage
{
facebook.Components.FacebookService _fbService = new facebook.Components.FacebookService();
private const string FACEBOOK_APPKEY = "66a8278bb94d969247a80815bab686e5"; // From the Facebook application page
private const string FACEBOOK_SECRET = "de76280e4ddaef72ac2166afe7ffb9d5"; // From the Facebook application page
protected void Page_PreInit(object sender, EventArgs e)
{
base.RequireLogin = false;
_fbService.IsDesktopApplication = false;
_fbService.ApplicationKey = FACEBOOK_APPKEY;
_fbService.Secret = FACEBOOK_SECRET;
_fbService.IsDesktopApplication = false;
_fbService.ConnectToFacebook();
abc.InnerText = _fbService.users.getInfo().ToString();
}
and it is throwing and Exception in the last line that that the object reference is not set.
You will need to host your production application somewhere, but you can test locally. If you set your Canvas URL to http://localhost:81 in Facebook, this should work. It did for me a couple of months ago, but they may have changed it since then.
this might be an interesting for you:
http://www.stevetrefethen.com/blog/DevelopingFacebookapplicationsinCwithASPNET.aspx
I have restricted access to a site by using Integrated Windows Authentication and turning off anonymous access. This way I can then show them their real name (from looking up on Active Directory and using the server variable LOGON_USER) and do other related Active Directory tasks.
How can I then prompt again for their user credentials, through a 'sign in as other user' link , showing the browser prompt (like you would get on a browser like Chrome or Firefox, or if the site was not in the 'Intranet' zone in IE) rather than a Web Form?
Since SharePoint offers this functionality, I assume there is a way to do this through code, but I don't know what code can do this (using C#). I can send a 401 header which makes the prompt appear, but how do you then confirm if they are logged in?
Maybe this can help you out.
ASP .NET – C# – How to “Sign in as Different User” like in Microsoft SharePoint with Windows Authentication
Try this approach. It is based on disassembled code of the method Microsoft.SharePoint.ApplicationPages.AccessDeniedPage.LogInAsAnotherUser()
First of all, I'm accessing the AccessDeniedPage page using javascript because Sharepoint does something similar:
function GoToSignAs() {
window.location.replace("./SignAs.aspx?signAs=true&returnUrl=" + window.location.toString());
}
<a onclick="GoToSignAs(); return false;" href="javascript:;">SignAs</a>
Then, in your page AccessDeniedPage you use this:
public partial class SignAs : Page
{
private const string LoginAttempts = "LoginAttempts";
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
HttpContext current = HttpContext.Current;
if (current == null)
{
throw new InvalidOperationException();
}
if (GetUrlParameter<bool>("signAs"))
{
HandleSignAs(current, GetUrlParameter<string>("returnUrl"));
}
}
// ...
private static void HandleSignAs(HttpContext context, string returnUrl)
{
int attempts = 0;
HttpCookie attemptsCookie = context.Request.Cookies[LoginAttempts];
if (attemptsCookie == null || string.IsNullOrEmpty(attemptsCookie.Value))
{
attemptsCookie = new HttpCookie(LoginAttempts);
}
else
{
attempts = int.Parse(attemptsCookie.Value, CultureInfo.InvariantCulture);
}
if (!string.IsNullOrEmpty(context.Request.Headers["Authorization"]))
{
// Attempts are counted only if an authorization token is informed.
attempts++;
}
if (attempts>1)
{
attemptsCookie.Value = string.Empty;
context.Response.Cookies.Add(attemptsCookie);
context.Response.Redirect(returnUrl, true);
}
else
{
attemptsCookie.Value = attempts.ToString(CultureInfo.InvariantCulture);
context.Response.Cookies.Add(attemptsCookie);
SendEndResponse(context, 401, "401 Unauthorized");
}
}
private static void SendEndResponse(HttpContext context, int code, string description)
{
HttpResponse response = context.Response;
context.Items["ResponseEnded"] = true;
context.ClearError();
response.StatusCode = code;
response.Clear();
response.StatusDescription = description;
response.AppendHeader("Connection", "close");
response.AddHeader("WWW-Authenticate", "Negotiate");
response.AddHeader("WWW-Authenticate", "NTLM");
response.End();
}
}
FIX: you must use the IIS to work properly