开发者

Console apps and extended permission offline_access workflow

I'm trying to get the Facebook C# SDK to work with offline_access and a console application.

From what I understand, I have to:

  1. Ask for auth for offline_access - that's easy.
  2. Get the "code" that is returned by FB when the user authorizes offline_acces开发者_如何学JAVAs
  3. Use ExchangeCodeForAccessToken to get a valid access token each time

I can't figure out how to grab the code in (2) though?

Thanks


Getting the "code" and exchanging the code for a token is something you usually do if you are doing authentication in a server-side workflow. It may be a bit of a red herring in your scenario. There are easier ways to just get the access token directly.

It would help to have more context (including code) showing how you are getting offline_access (javascript, server-side OAuth, ...?)

When you get offline_access via the Javascript SDK, which in my opinion provides the best user experience, you will get the access token back in the response from Facebook:

FB.login(function (response) {
    if (response.session) {
        if (response.perms) {
            var accesstoken = response.session.access_token;
            // do something with the token...save it, use it, etc.
        } else {
            // re-prompt for permissions
        }
    } 
}, { perms: 'offline_access' });

Once you have it in javascript you can stuff it into a hidden form field, put it in an ajax post to your server, or whatever.

Note that in my experience you do not actually need the saved user access token to do offline api calls for all api methods. You can just use an app access token in some cases, and Facebook will let it fly if you have offline_access and the other required permissions. They did post a developer blog post in the last week stating you need a token for some api calls where it was not previously required, so that might be changing.

Also be aware that these tokens can go bad. For example if the user changes their Facebook account password it invalidates all access tokens. So it is good to test them, catch OAuth exceptions, and have a way to bring this to the user's attention to re-prompt for permissions and get a new access token.


After the user grants you the "offline_access" permission, Facebook will redirect the user to your application URL with a "code" query string parameter. You need to grab this "code" query string parameter.

Then, make another WebRequest using this "code" value to get the access token. Use the following URL to make the request:

https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}

The WebResponse can be parsed like this:

NameValueCollection qs = HttpUtility.ParseQueryString(response);
token = qs["access_token"];

You need to persist the token in a database for use in your console application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜