如何从C#中的Facebook SDK获取当前用户访问令牌?不是应用访问令牌

时间:2018-11-20 09:58:55

标签: c# asp.net-mvc facebook-sdk-4.0 facebook-sdk-3.0

以下代码显示获取应用访问令牌

public static string GetAppAccessToken()
    {
        var fb = new FacebookClient();

        dynamic result = fb.Get("oauth/access_token", new
        {
            client_id = "****************",
            client_secret = "*******************",
            grant_type = "client_credentials"
        });

        return result.access_token;
    }

但是如何获取使用C#的Facebook SDK登录的当前用户的访问令牌

1 个答案:

答案 0 :(得分:1)

    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Script.Serialization;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Facebook;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;    

        public class AccessUser
        {
            public string access_token { get; set; }
            public string token_type { get; set; }
            public string expires_in { get; set; }
        }

        private void CheckAuthorization()
            {
                string app_id = "**************";
                string app_secret = "************************";

                if (Request["code"] == null)
                {
                    var redirectUrl = string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}", app_id, Request.Url.AbsoluteUri);
                    Response.Redirect(redirectUrl);
                }
                else
                {
                    AccessUser au = new AccessUser();

                    string url = string.Format("https://graph.facebook.com/v3.2/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}", app_id, Request.Url.AbsoluteUri, app_secret, Request["code"].ToString());

                    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        StreamReader reader = new StreamReader(response.GetResponseStream());
                        string vals = reader.ReadToEnd();
                        au = JsonConvert.DeserializeObject<AccessUser>(vals);
                        string token = au.access_token;

                    }
                }
            }

上面的代码将返回用户令牌。

注意:它是使用 aspx页构建的,它基于V3.2 Graph API调用。像1和2这样的版本,我们需要在URI中发送 Scope

如果有人需要源代码,请告诉我...