Facebook C#SDK获取用户accessToken
本文关键字:accessToken 用户 获取 C#SDK Facebook | 更新日期: 2023-09-27 17:58:06
我在从登录facebook的结果中获取accessToken时遇到问题。在Page_load中,我的url没有得到正确解析。
GenerateLoginUrl方法正在正常工作,并且我可以在QueryString中看到accessToken。我试着从中得到它,但它也不起作用。
protected void Page_Load(object sender, EventArgs e)
{
var fb = new FacebookClient();
FacebookOAuthResult result;
if (fb.TryParseOAuthCallbackUrl(Request.Url, out result))
{
if (result.IsSuccess)
{
// result clicked authorized
var accessToken = result.AccessToken;
Label1.Text = accessToken.ToString();
}
else
{
// user clicked cancelled and didn't authorize the app
var error = result.ErrorDescription;
Label1.Text = error;
}
}
else
{
//This is were it always goes
Label1.Text = "not valid facebook url";
}
}
private Uri GenerateLoginUrl(string appId, string extendedPermissions)
{
try
{
dynamic parameters = new ExpandoObject();
parameters.client_id = appId;
parameters.redirect_uri = "local iis ip";
// The requested response: an access token (token), an authorization code (code), or both (code token).
parameters.response_type = "token";
// list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
parameters.display = "popup";
// add the 'scope' parameter only if we have extendedPermissions.
if (!string.IsNullOrWhiteSpace(extendedPermissions))
parameters.scope = extendedPermissions;
// generate the login url
var fb = new FacebookClient();
var url = fb.GetLoginUrl(parameters);
return url;
}
catch (FacebookOAuthException fbex)
{
Label1.Text = fbex.Message;
return null;
}
catch (Exception ex)
{
Label1.Text = ex.Message;
return null;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string AppId = ConfigurationManager.AppSettings["apiKey"];
string ExtendedPermissions = ConfigurationManager.AppSettings["ExtendedPermissions"];
var url = GenerateLoginUrl(AppId, ExtendedPermissions);
Response.Redirect(url.AbsoluteUri, false);
}
谢谢你的帮助。
更新:
在Request.Url中,Url始终为:
http://localhost:23560/Appname/default.aspx
但我可以在浏览器中找到真正的url,它是:
http://localhost:23560/Appname/#access_token=0000000000&expires_in=3821
这样一来,asp.net就不能正确读取网址了吗?
我找到了answare,它是:
你必须得到代码而不是令牌,代码将显示在querystring中。accesstoken被剥离。
parameters.response_type = "token";
交换
parameters.response_type = "code";
然后交换到代码以标记
dynamic token = fb.Get("oauth/access_token", new
{
client_id = "appid",
client_secret = "appsecret",
redirect_uri = url,
code = Request.QueryString["code"]
});
var accessToken=token.access_token;