问题
I am using The Facebook-C#-Sdk v5.0.3 to create a non-canvas webforms app in vb.net and i am having trouble exchanging the returned facebook code for the access_token. Does anyone have an example (C# or vb.net) that I can look at?
Thanks awesome Stackoverflow community!
回答1:
Try this:
var app = new FacebookClient(FacebookContext.Current.AppId, FacebookContext.Current.AppSecret);
var accessToken = app.AccessToken
or this:
var app = new FacebookClient(new Authorizer().Session.AccessToken);
var accessToken = app.AccessToken
回答2:
You can use the appId and appSecret as the app accesstoken.
For instance you can do this when debugging an user token to see if it's valid
var client = new FacebookClient();
dynamic result = client.Get("debug_token", new
{
input_token = user.AccessToken,
access_token = string.Format("{0}|{1}", appId, appSecret)
});
Later you can check result.data.is_valid to see if the user token is still valid.
If you need the access_token of a user, you first need to set the scope correctly, later you can do this:
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
appId, Request.Url.AbsoluteUri, scope));
}
else
{
var tokens = new Dictionary<string, string>();
string url =
string.Format(
"https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
appId, Request.Url.AbsoluteUri, scope, Request["code"], appSecret);
var request = WebRequest.Create(url) as HttpWebRequest;
using (var response = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
// Get access token from tokens
var accessToken = tokens["access_token"];
}
This will redirect the user to Facebook asking for permission. Then Facebook will return to the return URL with code in the querystring, use that code to retreive the user's access_token.
Keep in mind this will be a short-lived access_token, you will probably have to expand it.
来源:https://stackoverflow.com/questions/5070130/exchange-code-for-token-facebook-c-sdk