get an access token using Facebook C# SDK

二次信任 提交于 2019-12-06 11:55:20

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!