Hi i am using the following code to get access token from facebook using C# SDK
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = "clientId",
client_secret = "clientSecret",
redirect_uri = "redirectUri",
code = "code"
});
return result.access_token;
the above code works perfect most of the time but some times i gets this error
(OAuthException - #100) Invalid verification code format.
how to fix this problem??
What is your project type : WinForms , WPF , ASP.NET ?
if you are working with WinForms or WPF , you have to get the access_token form the Browser Control URL by requesting the OAuth Login Dialog and the return_type=token , then extract the valid access_token from the URL.
Otherwise , if you are working on Web Application using ASP.NET , you will have to redirect the user to the OAuth Dialog Login Page then the facebook will redirect you back with a code on the URL , you get this code from the QueryString and make an HTTPRequest to the Facebook to get the valid access_token .
you can use my method for doing that :
public string GetAccessTokenFromCode(string AppID, string AppSecret, string RedirectURL, string Code)
{
WebClient wc = new WebClient();
string u2 = "https://graph.facebook.com/oauth/access_token?client_id=" + AppID + "&redirect_uri=" + RedirectURL + "&client_secret=" + AppSecret + "&code=" + Code + "&state=anytexthere";
string access = wc.DownloadString(u2);
access = access.Substring(access.IndexOf("access_token") + 13);
if (access.Contains("&"))
{
string accesstoken = access.Substring(0, access.IndexOf("&"));
return accesstoken;
}
return access;
}
and you can call it from the Page_Load :
if (Request.QueryString["code"] != null)
{
code = Request.QueryString["code"].ToString();
string AT = GetAccessTokenFromCode(AppID, AppSecret, RedirectUrl, Code);
}
You should have the same redirect_uri as you did when asking for code.
Also there must be a trailing slash '/' at the end of the site url you configured in 'Website with Facebook Login' section on Facebook.
Here's a complete tutorial: Working with C# SDK
This page makes me wonder if your code should look more like this:
dynamic result = fbClient.Get("oauth/access_token", new
{
client_id = fbClient.AppId,
client_secret = fbClient.AppSecret,
grant_type = "fb_exchange_token",
fb_exchange_token = accessToken
});
Maybe your accessToken is timing out or something?
after downloading sdk from http://www.nuget.org/packages/Facebook.CSharp.SDK/
var config = new Dictionary<string, object>();
//your application id and secret from https://developers.facebook.com/apps
config.Add("appId", "3955.......");
config.Add("secret", "4c1d...............");
config.Add("fileUpload", true); //optional
FacebookClient client = new FacebookClient(config);
ulong facebookId = client.getUser(); //retrieve user id. if user is not added the app this value is 0
client.getAccessToken()
gives you the access token.
Related
I am developing a web API to handle realtime updates (Lead information) from Facebook to integrate with my CRM.
In the WEB API POST request, I am able to capture the leadID but the problem comes when I get leadinfo by invoking FB.Get(LeadID). To make a Graph API GET request(for lead information) I need to have a user access token and this is where i have been struggling for quite sometime. I have looked up several posts online but havent got any solution for my problem.
In my sample implementation, GetLoginUrl(parameters) returns a uri and when when I request the uri in a browser, I see that the access token gets generated in the redirected Uri. But how to do this programatically ? I have tried the following
string FBAccessUrl = "https://graph.facebook.com/oauth/authorize?client_id=XXXXXXXXXXXX&response_type=token&redirect_uri=https://www.facebook.com/connect/login_success.html";
var accessTokenRequest = System.Net.HttpWebRequest.Create(FBAccessUrl);
HttpWebResponse response = (HttpWebResponse)accessTokenRequest.GetResponse();
but then i get this ResponseUri = {https://www.facebook.com/unsupportedbrowser} which is not what I want.
Can someone help me with how the user access token can be generated using C# in the Web API (without the facebook login dialog)
[HttpPost]
[ActionName("Complex")]
public void PostComplex(RootObject root)
{
FacebookClient fb = new FacebookClient();
// Get leadID from the inital HTTP POST request
long leadgen_id = root.entry[0].changes[0].value.leadgen_id;
string leadID = leadgen_id.ToString();
// to get user access token
dynamic parameters = new ExpandoObject();
parameters.client_id = "XXXXXXXXXXXXXXX";
parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
parameters.response_type = "token";
// generate the login url
Uri uri = fb.GetLoginUrl(parameters);
// reuest the uri in browser and uri2 is the redirected uri
Uri uri2 = "****************"
string accesstoken = "";
FacebookOAuthResult oauthResult;
if (fb.TryParseOAuthCallbackUrl(uri, out oauthResult))
{
if (oauthResult.IsSuccess)
{
accesstoken = oauthResult.AccessToken;
}
else
{
var errorDescription = oauthResult.ErrorDescription;
var errorReason = oauthResult.ErrorReason;
}
}
fb.AccessToken = accesstoken;
string me = fb.Get(leadID).ToString();
// Then fetch required lead information
}
I'm trying to understand if it is possible to post on the users' wall from my Facebook application.
At the moment I have:
One Facebook app with the permission to write on the users' wall
A BackEnd with Fairbooks SDK Installed
Actually I'm following this approach:
public static string GetToken()
{
var fb = new Facebook.FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = APP_ID,
client_secret = APP_S,
grant_type = "client_credentials"
});
return result.access_token;
}
public static void Post(string Message, long UserID)
{
var token = GetToken();
var client = new FacebookClient(token);
client.Post("/" + UserID + "/photos", new { url = "url", caption = Message });
}
My final goal is to post on facebook when the user interact with my API without client-side popups. Is this possible?
This line of code calls for an application access token
dynamic result = fb.Get("oauth/access_token", new
{
client_id = APP_ID,
client_secret = APP_S,
grant_type = "client_credentials"
});
It makes no sense to use this if you haven't first retrieved a user access token in advance. Only then can you make calls on behalf of the user.
My final goal is to post on facebook when the user interact with my API without client-side popups. Is this possible?
This will never be possible by design. All 3rd party applications must invoke a client-side activity for the user in some format. It cannot be automated.
when trying to redirect to gain a new access token an error occurred saying :
(OAuthException - #190) Malformed access token AQClEC8NbS1tbO4_HzqqZwVy2Inrk5I7vBpszPDPN0dVOV0ekurwNEpqzlWe2hQzl2KNZ5BwiSvL16bDPhR5IxFeJXEXBdM67uky7iwKbYKIVoRF__iyayyXBgcIp939gEZNtCUxyO4ZKZHQ9xmEwDstaOgq_bAvtygwv3YUeEYD9wftsytMZYwVxDO7rjq-2i3-XCYj643-6_1yKZ0dDahAB00iBqJqw1xiZ-l1kzStmA_pwMwO5dtBHZozp-L2hp0JEeTL0Fhc5CG1zbJ8Om6kyKBWyZuc0AtOrdSjgcBQBv9hQSF5pwsMZvFDGcjiwSc
what possibly could be the problem i am doing this method to redirect :
string redirecturl = #"https://graph.facebook.com/oauth/authorize?client_id=507061112747022&redirect_uri=http://localhost:63695/FacebookChatApi/Default.aspx";
Response.Redirect(redirecturl);
and i am reading the access token as follow :
string accessToken=Request["code"];
var client = new FacebookClient(accessToken); // here is where the error occurred
Is this the right method to get a client access token ?
why this error is occurring when reading the code value
according to Facebook Debug tool, your token is not a Token but a URL instead: https://developers.facebook.com/tools/debug/og/object?q=AQClEC8NbS1tbO4_HzqqZwVy2Inrk5I7vBpszPDPN0dVOV0ekurwNEpqzlWe2hQzl2KNZ5BwiSvL16bDPhR5IxFeJXEXBdM67uky7iwKbYKIVoRF__iyayyXBgcIp939gEZNtCUxyO4ZKZHQ9xmEwDstaOgq_bAvtygwv3YUeEYD9wftsytMZYwVxDO7rjq
I'm not sure who you get it, and why you get it instead of access token - you did not show enough code. From what I saw, I believe you generate your redirecturl incorrectly. Below is a piece of code from one of my project - please try it and let me know if it works for you:
// 1. redirect user to the login page:
var redirectUri = "http://localhost:63695/FacebookChatApi/Default.aspx";
var service = new FacebookClient();
var loginUrl = service.GetLoginUrl(new {
client_id = ConfigurationProvider.FacebookAppId,
client_secret = ConfigurationProvider.FacebookAppSecret,
redirect_uri = redirectUri,
response_type = "code",
scope = "manage_pages, publish_actions, user_photos, publish_stream" // Add other permissions as needed
});
Response.Redirect(loginUrl);
// 2. And when user authorizes, get the access token
// NOTE: code executes on FacebookChatApi/Default.aspx page
var redirectUri = "http://localhost:63695/FacebookChatApi/Default.aspx"; // must be the same as in the login call!
var fb = new FacebookClient();
dynamic result = fb.Post("oauth/access_token", new
{
client_id = ConfigurationProvider.FacebookAppId,
client_secret = ConfigurationProvider.FacebookAppSecret,
redirect_uri = redirectUri,
code = code
});
var accessToken = result.access_token;
I am developing a Windows Store App which requires user to authenticate using Yammer credentials. I have written the following code to achieve the functionality.
var client_id = <<My Client ID >>;
var client_secret = <<My Client Secret>>;
string redirectURI = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();
string loginURI = "https://www.yammer.com/dialog/oauth?client_id=" + client_id + "&redirect_uri=" + redirectURI;
var result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, new Uri(loginURI), new Uri(redirectURI));
if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
var response = result.ResponseData;
string[] keyValPairs = response.Split('=');
HttpClient client = new HttpClient();
string url = "https://www.yammer.com/oauth2/access_token.json?client_id=" + client_id + "&client_secret=" + client_secret + "&code=" + keyValPairs[1];
HttpResponseMessage JSONresponse = await client.GetAsync(url);
string content = await JSONresponse.Content.ReadAsStringAsync();
}
When I ran the app for the first time it asked me for my credentials and I was able to login.
Now when I run my app , it takes my previous entered credentials and logs in automatically. I am sure that I did not check "Keep Me signed In" option.
I want the app to ask for credentials every time I run it.
Please help and thanks in advance.
I had a similar problem with an app using the Pocket OAUTH 2.0 API. I am using the WebAuthenticationBroker http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.authentication.web.webauthenticationbroker.aspx and its AuthenticateAsync method but I think the problem is the same.
I had used the AuthenticateAsync(options, url) method which ended up -once credentials are saved - I was never able to use a different login so basically could not change accounts.
Tried AuthenticateAsync(options, url, redirectURI) method and same problem.
But then I realized that redirectURI is set to GetCurrentApplicationCallbackUri as in your example this seems to trigger SSO.
Changing the redirectURI to a custom one (e.g. your own domain) seems to disable SSO and credentials have to be added every time as wanted.
This is easy with the AuthenticateAsync method as it uses a WebAuthenticationBroker, not sure how to adapt this with the HttpClient you use above but I maybe you could use
WebAuthenticationBroker?
But my code example (Javascript but same API):
var authweb = Windows.Security.Authentication.Web
var OAUTH_URI = 'https://$WHATEVERSERVICE'
var OAUTH_CODE = '$GOT BEFORE'
var endURI = 'http://$YOURDOMAIN.com' // this is the important part
var authorizeUri = new Windows.Foundation.Uri(OAUTH_URI
+ '?request_token=' + encodeURIComponent(OAUTH_CODE) // POCKET SPECIFIC PARAM
+ '&redirect_uri=' + encodeURIComponent(endURI)
);
authweb.WebAuthenticationBroker.authenticateAsync(
authweb.WebAuthenticationOptions.none,
authorizeUri,
Windows.Foundation.Uri(endURI)
).done(...
This way I get a clean (no prefilled or even submitted) login form every time.
Hope this helps?
I'm developing a desktop application in C#.
After visiting https://www.facebook.com/dialog/oauth?client_id=123 the user logs in and the user access token is attached to the redirect uri. Its no problem, when the loginpage is displayed in a webbrowser control in my form, so i can extract the token from the url.
But this is not the way i want to get the token. My question is, is there a way to obtain the freshly created token via an Graph API call?
Because i want to display the login page in the user's standard browser and not in this embedded webbrowser. All my efforts to get the user access token have been resulted in getting the app access token, which is useless in this case.
Any hints are appreciated.
// This is very raw, And Note it is a MVC3 solution, but it is in C# and I hope it helps.
// It is basically a C# version of the PHP example on FB for 'Server Side Flow'
// I have been at it for a while and had to go through some pain
// Please note the bug I read about that states the redirect_uri must be the same for both //requests
// Also read that someone had an issue if the redirect_uri did not end in '/'
// Post back if you hae any ?s as I am just starting this project and am going to try and //incorporate the C# FaceBook SDK
public class AccountController : Controller
{
// LoginWithFaceBook
// First Contact with FB - oauth?client_id ... redirect_uri = /Account/FacebookLinker
// according to a bug files on FB redirect_uri MUST BE SAME FOR both trips ( to get the 'code' then exchange the code for 'access_token'
public ActionResult ConnectFaceBookAccount()
{
string APP_ID = HttpContext.Application["FacebookAppId"].ToString();
string redirect_uri = HttpContext.Application["FacebookOAuthRedirect"].ToString();
string state = HttpContext.Application["state_guid"].ToString();
// in this View I simply link to this URL
ViewBag.FaceBookOAuthUrl = "https://www.facebook.com/dialog/oauth?client_id=" + APP_ID + "&redirect_uri="+redirect_uri+"&state=" + state+"&display=popup";
return View();
}
// Account/FacebookLinker
// redirect_uri for both getting 'code' and exchanging for 'access_token'
public ActionResult FacebookLinker()
{
if (!Request.IsAuthenticated)
{
Response.Redirect("/Account/LogOn");
}
// Per FB DOC, Make sure 'state' var returned is same one you sent to reduce chance of Cross Site Forgery
if (Request.QueryString["state"].ToString() == HttpContext.Application["state_guid"].ToString())
{
try
{
string FBcode = Request.QueryString["code"].ToString();
string APP_ID = HttpContext.Application["FacebookAppId"].ToString();
string APP_SECRET = HttpContext.Application["FacebookAppSecret"].ToString();
string redirect_uri = HttpContext.Application["FacebookOAuthRedirect"].ToString();
string FBAccessUrl = "https://graph.facebook.com/oauth/access_token?client_id=" + APP_ID + "&redirect_uri=" + redirect_uri + "&client_secret=" + APP_SECRET + "&code=" + FBcode;
string accessToken = null;
// Send the request to exchange the code for access_token
var accessTokenRequest = System.Net.HttpWebRequest.Create(FBAccessUrl);
HttpWebResponse response = (HttpWebResponse) accessTokenRequest.GetResponse();
// handle response from FB
// this will not be a url with params like the first request to get the 'code'
Encoding rEncoding = Encoding.GetEncoding(response.CharacterSet);
using(StreamReader sr = new StreamReader(response.GetResponseStream(),rEncoding))
{
// parse the response to get the value of the 'access_token'
accessToken = HttpUtility.ParseQueryString(sr.ReadToEnd()).Get("access_token");
}
//TODO
// Add to the accessToken for the Logged in User.Identity to a FBUSERS Model
// WHen someone Logs in Check to see if they are also in FB
// ON Login Page add option to login with FaceBook
return View();
}
catch (Exception exp)
{
// try to get token failed
}
}
else
{
// state var form FB did not match state var sent
}
return View();
}
I think this is achievable via URL protocol handlers;
Create a custom URL protocol handler (MSDN: Registering an Application to a URL Protocol)
Create a facebook page that passes user access token to your url handler (ex. myfbapp://accesstoken/{token})
Set oauth redirect_uri to your facebook page
Parse access token in your application