【问题标题】:How to get an access token using C# SDK如何使用 C# SDK 获取访问令牌
【发布时间】:2012-04-11 23:38:06
【问题描述】:

我将 Facebook SDK 更新到 6.0.10,一些过去可以工作的代码不再工作了。我以前在用户的墙上发帖使用下面的方法。

FacebookClient 类用于获取AppIdAppSecret,但我没有为我的应用程序提供任何访问令牌。

string uId = "SomeUid";
FacebookClient fb = new FacebookClient(AppId,AppSecret );

string userFeedPath = String.Format("/{0}/feed", uId);

dynamic parameters = new ExpandoObject();
parameters.link = "Test@test";
parameters.message = "test";

try
{
    dynamic result = fb.Post(userFeedPath, parameters);
}
catch(Exception ex)
{

}

现在即使我试试这个,

FacebookClient fb = new FacebookClient();

fb.AppId = "1234...";
fb.AppSecret = "76e69e0c334995cecc8c....";

我收到此错误:

(OAuthException - #200) (#200) 此 API 调用需要有效的 app_id。

我该如何解决这个问题?

【问题讨论】:

  • 您能否确定您的凭据对于更新后的 SDK 仍然有效?您可能需要获取新的凭据(例如,由于正在使用的 OAuth 类型升级)。
  • 对于将来遇到问题的人,这里有一个完整的教程:Working with Facebook C# SDK

标签: c# facebook-c#-sdk


【解决方案1】:

您需要通过发出请求来获取应用访问令牌。

var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new { 
    client_id     = "app_id", 
    client_secret = "app_secret", 
    grant_type    = "client_credentials" 
});
fb.AccessToken = result.access_token;

【讨论】:

  • 这是否意味着 6.0 版有重大更改?我现在才开始使用 V 6.0,但我正在学习一个教程,但我无法让它工作......以前的类型不存在(查看 Codeplex 和旧版本有文件)。令人沮丧的不用说...
  • 嗨,普拉比尔。我没有任何运气就尝试了这种方法。首先,我认为应该是 result.access_token 来获取价值。但除此之外,这似乎将获得应用程序的访问令牌,而不是应用程序的特定用户。听起来获取用户访问令牌的唯一方法是通过 JavaScript SDK?那是对的吗?还是 C# SDK 提供了我缺少的其他方式?谢谢!
  • 谢谢。我更新为 result.access_token。它用于应用访问令牌。对于用户访问令牌,您需要使用服务器端流程或使用 js sdk。
  • @prabir 如果你的这个 sdk 有一个简明的文档,那就太棒了。使用这个 sdk 简直是折磨。
  • @DarthVader 这已经记录在csharpsdk.org/docs/faq.html 什么不起作用?你可以说得更详细点吗。如果有错误,您应该在 github 中打开问题。如果您想避免破坏性更改,请坚持使用 v5。
【解决方案2】:

对于代码 -> 服务器端流程中的用户访问令牌交换 - 改为(版本 5):

    FacebookOAuthClient oAuthClient = new FacebookOAuthClient();
    oAuthClient.AppId = "...";
    oAuthClient.AppSecret = "...";
    oAuthClient.RedirectUri = new Uri("https://.../....aspx");

    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
    return tokenResult.access_token;

现在使用(版本 6):

    Dictionary<string, object> parameters = new Dictionary<string, object>();
    parameters.Add("client_id", "...");
    parameters.Add("redirect_uri", "https://.../....aspx");
    parameters.Add("client_secret", "...");
    parameters.Add("code", code);

    result = fb.Get("/oauth/access_token", parameters);

    string accessToken = result["access_token"];

(见:http://developers.facebook.com/docs/authentication/server-side/

【讨论】:

  • 完全按照您的代码,我得到:(OAuthException - #101) 验证应用程序时出错。由于系统错误,无法获取应用程序信息。
  • 我认为要点是需要发生回调。这意味着您必须提供一个接受“code”参数并将其应用于用户的重定向 url。
  • 什么是code变量?我如何获得代码价值?
  • 回答不完整。我不知道为什么这是一个答案
【解决方案3】:

我昨天刚刚开始使用这个 Facebook 库,并认为无法在不通过 JavaScript 的情况下向我提供访问令牌是一个主要缺点。这是一个可以获取访问令牌的助手。我希望这可以帮助任何和我有同样挫折感的人。我认为这应该一切正常。在我发现 Facebook NuGet 之前,我在一个网站上做过类似的工作,它已经运行了大约一年。

如果有更好的方法请告诉我。

public class FacebookHelper
{
    private string _appId;
    private string _appSecret;
    private string _accessToken;

    public string AccessToken
    {
        get
        {
            if (_accessToken == null)
                GetAccessToken();

            return _accessToken;
        }
        set { _accessToken = value; }
    }

    public FacebookHelper(string appId, string appSecret)
    {
        this._appId = appId;
        this._appSecret = appSecret;
    }

    public string GetAccessToken()
    {
        var facebookCookie = HttpContext.Current.Request.Cookies["fbsr_" + _appId];
        if (facebookCookie != null && facebookCookie.Value != null)
        {
            string jsoncode = System.Text.ASCIIEncoding.ASCII.GetString(FromBase64ForUrlString(facebookCookie.Value.Split(new char[] { '.' })[1]));
            var tokenParams = HttpUtility.ParseQueryString(GetAccessToken((string)JObject.Parse(jsoncode)["code"]));
            _accessToken = tokenParams["access_token"];
            return _accessToken;
        }
        else
            return null;

       // return DBLoginCall(username, passwordHash, cookieToken, cookieTokenExpires, args.LoginType == LoginType.Logout, null);
    }

    private string GetAccessToken(string code)
    {
        //Notice the empty redirect_uri! And the replace on the code we get from the cookie.
        string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}", _appId, "", _appSecret, code.Replace("\"", ""));

        System.Net.HttpWebRequest request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
        System.Net.HttpWebResponse response = null;

        try
        {
            using (response = request.GetResponse() as System.Net.HttpWebResponse)
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());

                string retVal = reader.ReadToEnd();
                return retVal;
            }
        }
        catch
        {
            return null;
        }
    }

    private byte[] FromBase64ForUrlString(string base64ForUrlInput)
    {
        int padChars = (base64ForUrlInput.Length % 4) == 0 ? 0 : (4 - (base64ForUrlInput.Length % 4));
        StringBuilder result = new StringBuilder(base64ForUrlInput, base64ForUrlInput.Length + padChars);
        result.Append(String.Empty.PadRight(padChars, '='));
        result.Replace('-', '+');
        result.Replace('_', '/');
        return Convert.FromBase64String(result.ToString());
    }
}

【讨论】:

  • 这看起来很有希望,你能告诉我更多吗?我在我的 cookie 列表中没有看到 fbsr_[appId] cookie
【解决方案4】:

还有另一种无需使用生成的应用访问令牌即可调用 Graph API 的方法。您可以在拨打电话时将您的应用 ID 和应用密码作为 access_token 参数传递:

https://graph.facebook.com/endpoint?key=value&access_token=app_id|app_secret

使用生成的访问令牌与此方法的选择取决于 隐藏应用机密的位置。

发件人:https://developers.facebook.com/docs/facebook-login/access-tokens

var client = new FacebookClient($"{appId}|{appSecret}");

【讨论】:

    【解决方案5】:

    我尝试了上面的一些示例,只是发现 dynamic 不能使用 xamarin studio 编译。这就是我所做的。

    public class AccessTokenModel
    {
        public string Access_Token { get; set;}
    }
    
    var fb = new FacebookClient();
    var result = fb.Get ("oauth/access_token", new { 
        client_id     = App.FaceBookId, 
        client_secret = App.FacebookAppSecret, 
        grant_type    = "client_credentials" 
    });
    var accessToken = Newtonsoft.Json.JsonConvert.DeserializeObject<AccessTokenModel> (result.ToString ());
    

    FBSession.ActiveSession.AccessTokenData.AccessToken;
    

    【讨论】:

    • 我使用 WinForms 和单元测试项目。什么是 FBSession?
    【解决方案6】:

    野兔是一种真正的工作方法:

    protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
            {
                // Note: Facebook doesn't like us to url-encode the redirect_uri value
                var builder = new UriBuilder("https://graph.facebook.com/oauth/access_token");
                builder.AppendQueryArgument("client_id", this.appId);
                builder.AppendQueryArgument("redirect_uri", NormalizeHexEncoding(returnUrl.GetLeftPart(UriPartial.Path)));
                builder.AppendQueryArgument("client_secret", this.appSecret);
                builder.AppendQueryArgument("code", authorizationCode);
    
                using (WebClient client = new WebClient())
                {
                    //Get Accsess  Token
                    string data = client.DownloadString(builder.Uri);
                    if (string.IsNullOrEmpty(data))
                    {
                        return null;
                    }
    
                    var parsedQueryString = HttpUtility.ParseQueryString(data);
                    return parsedQueryString["access_token"];
                }
            }
     private static string NormalizeHexEncoding(string url)
            {
                var chars = url.ToCharArray();
                for (int i = 0; i < chars.Length - 2; i++)
                {
                    if (chars[i] == '%')
                    {
                        chars[i + 1] = char.ToUpperInvariant(chars[i + 1]);
                        chars[i + 2] = char.ToUpperInvariant(chars[i + 2]);
                        i += 2;
                    }
                }
                return new string(chars);
            }
    

    【讨论】:

    • 如何获得authorizationCode
    猜你喜欢
    • 2017-01-07
    • 2015-10-11
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    相关资源
    最近更新 更多