C# Facebook SDK extend an accesstoken to 60 days

跟風遠走 提交于 2019-12-05 04:23:04

问题


The main question: How am I supposed to extend the 2 hour access token for the 60 day access token via the C# SDK? Can you provide a sample of just that section where the code has already been traded for the 2 hour access token?

Background: I've been looking around on here and trying various solutions and haven't found one that works for me yet. I can successfully make the /me call and get the information about the current user however when I try to extend the access token it fails.

The goal of this app is to allow a user to set up a post and to monitor likes and comments after the fact for a set period of time. We need the 60 day token for this, obviously.

I am taking this project over after someone else did 90% of the work when you could request the permanent token. It's my job to fix it so that we can use the 60 day token. I may ask very stupid follow up questions. Be prepared!

The current flow: The user sets up his post, clicks a button, we prompt them to auth our app/log into facebook via the javascript sdk. After they log in we process other unrelated things in javascript and then AJAX it over to C# to save some information to our database (including the token) and make the post. Everything goes great, I get the access token just fine in javascript and I can use that 2 hour token to get info on the user who's logged in however when I try to extend I get one of two errors which I'll mention below with the code that causes them.

What I've tried:

Working: I believe I found this in another post here. var fbClient = new FacebookClient(accessToken);

            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("client_id", appId);
            parameters.Add("redirect_uri", redirectURI);
            parameters.Add("client_secret", appSecret);
            parameters.Add("code", accessToken);

            var result = fbClient.Get("/me", parameters);

Not working: This came from various places including here and the sdk docs. I've seen people including the redirect url and saying it needs to match the one when you originally got the accesstoken but we did that in javascript and didn't use a redirect url. Dictionary parameters2 = new Dictionary();

            parameters2.Add("client_id", appId);
            //parameters2.Add("redirect_uri", redirectURI);
            parameters2.Add("client_secret", appSecret);
            //parameters2.Add("code", accessToken);
            parameters2.Add("grant_type", "fb_exchange_token");
            parameters2.Add("fb_exchange_token", accessToken);

            var result2 = fbClient.Get("/oauth/access_token", parameters2);

Error: {Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: a. Line 1, position 1. Error2: If I comment out grant_type and fb_exchange_token and uncomment code and the redirecturi I get the same error as the next method...

Not working: This I grabbed from another post here copy/paste rename to match my vars. Unable to get long lived expiration token

            dynamic result3 = new ExpandoObject();
            try
            {
                dynamic parameters3 = new ExpandoObject();
                parameters3.grant_type = "fb_exchange_token";
                parameters3.fb_exchange_token = accessToken;
                parameters3.client_id = appId;
                parameters3.client_secret = appSecret;
                result3 = fbClient.Get("oauth/access_token", parameters);
            }
            catch (FacebookOAuthException err)
            {
                result3.error = "Error";
                result3.message = err.Message;
            }
            catch (Exception err)
            {
                result3.error = "Error";
                result3.message = err.Message;
            }

Error: {(OAuthException) (OAuthException) Invalid verification code format.}


回答1:


Use the following code with Facebook.NET and Json.NET in a handler file that is your callback.

public void ProcessRequest (HttpContext context)
    {
        if (context.Request.Params.Get("error_reason") == "user_denied")
        {
            context.Response.Write("Access Denied");
        }
        else if (context.Request.Params.Get("code") != null && context.Request.Params.Get("code") != "")
        {
            string shorttoken = HttpUtility.ParseQueryString(HttpUtil.GetHtmlPage("https://graph.facebook.com/oauth/access_token?client_id=" + APP_ID + "&redirect_uri=http://huadianz.me/mvp/auth/FacebookOAuth.ashx&client_secret=" + APP_SECRET + "&code=" + context.Request.Params.Get("code")))["access_token"];
            string longtoken = HttpUtility.ParseQueryString(HttpUtil.GetHtmlPage("https://graph.facebook.com/oauth/access_token?client_id=" + APP_ID + "&client_secret=" + APP_SECRET + "&grant_type=fb_exchange_token&fb_exchange_token=" + shorttoken))["access_token"];

            Facebook.FacebookClient fc = new Facebook.FacebookClient(longtoken);
            dynamic result = fc.Get("me");

            context.Response.Redirect("/");
            //Store Token here
        }
    }

My Utilities file is here:

public static class HttpUtil
{
    public static string GetHtmlPage(string strURL)
    {
        String strResult;
        WebResponse objResponse;
        WebRequest objRequest = HttpWebRequest.Create(strURL);
        objResponse = objRequest.GetResponse();
        using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
        {
            strResult = sr.ReadToEnd();
            sr.Close();
        }
        return strResult;
    }
}



回答2:


See How to renew Facebook access token using its C# SDK. Just requesting "oauth/access_token" isn't enough, you have to specify parameters there too. The technique there worked for me.



来源:https://stackoverflow.com/questions/12101445/c-sharp-facebook-sdk-extend-an-accesstoken-to-60-days

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