在Facebook集成我必须访问其中的访问令牌给出的url,而是我得到我在asp.net发布的url

本文关键字:url net asp 集成 Facebook 访问 访问令牌 | 更新日期: 2023-09-27 18:04:48

我在asp.net web应用程序的facebook_login页面的Page_Load上使用以下代码。重定向此url后,我在url中获得了accesstoken,但当我尝试通过HttpContext.Current.Request.Url.AbsoluteUri访问此当前url时,它给出了发布的应用程序的url,而不是当前在窗口中的url。

我如何访问这个访问令牌或userdetails?

var uriParams = new Dictionary<string, string>() {
                    {"client_id", facebookAppId},
                    {"response_type", "token"},
                    {"scope", "user_about_me, read_stream, email"},
                    {"redirect_uri", "http://apps.facebook.com/appNameHere/"}
                }; 
        StringBuilder urlBuilder = new StringBuilder();
        foreach (var current in uriParams)
        {
            if (urlBuilder.Length > 0)
            {
                urlBuilder.Append("&");
            }
            var encoded = HttpUtility.UrlEncode(current.Value);
            urlBuilder.AppendFormat("{0}={1}", current.Key, encoded);
        }
        var loginUrl = "http://www.facebook.com/dialog/oauth?" + urlBuilder.ToString();
        Response.Redirect(loginUrl);

在Facebook集成我必须访问其中的访问令牌给出的url,而是我得到我在asp.net发布的url

在Facebook中,你可以设置回叫url值,它应该指向你的web应用程序。因此,一旦您向http://www.facebook.com/dialog/oauth发出请求并成功登录Facebook后,重定向到回调Url(这是您的web应用程序)。

然后你必须调用url: https://graph.facebook.com/oauth/access_token像这样:

        StringBuilder uri = new StringBuilder();
        uri.Append("https://graph.facebook.com/oauth/access_token?");
        uri.Append("client_id=" + ClientKey + "&");
        uri.Append("redirect_uri=" + Curl + "&");
        uri.Append("scope=offline_access&");
        uri.Append("client_secret=" + ClientSecret + "&");
        uri.Append("code=" + OAuthCode);
        HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
        req.Headers.Add("Authorization", String.Empty);            
        req.Method = "POST";
        req.ServicePoint.Expect100Continue = false;
        req.ContentLength = 0;
        req.ContentType = "application/x-www-form-urlencoded";
        HttpWebResponse resp;
        try
        {
            resp = (HttpWebResponse)req.GetResponse();
            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
            string result = sr.ReadToEnd().Trim();
            string[] resultCollection = Regex.Split(result, "&");
            string access_token = Regex.Split(resultCollection[0], "=")[1];//This is the access token
            //which you want and you can save it to database or some  where for further use.
        }
        catch (WebException ex)
        {
            resp = (HttpWebResponse)ex.Response;
            //pass on the exception
            throw ex;
        }

更新:

OAuthCode你可以得到这样,它是可用的,当成功登录FB重定向到你的web应用程序页面

OAuthCode = Request.Params["code"];

头可以设置为空,如String.Empty