Access Tokens
When someone connects with an app using Facebook Login and approves the reqest for permissions,
the app obtains an access token that provides temporary, secure access to Facebook APIs.
You can see a list of your access tokens and debugging information for each token in the Access Token Tool.
An access token is an opaque string that identifies a user, app, or Page and can be used by the app to make graph API calls.
Access tokens are obtained via a number of methods, each of which are covered later in this document.
The token includes information about when the token will expire and which app generated the token.
Because of privacy checks, the majority of API calls on Facebook need to include an access token.
There are different types of access tokens to support different use cases:
Access Token Type | Description |
---|---|
The user token is the most commonly used type of token. This kind of access token is needed any time the app calls an API to read, modify or write a specific person's Facebook data on their behalf. User access tokens are generally obtained via a login dialog and require a person to permit your app to obtain one. |
|
This kind of access token is needed to modify and read the app settings. It can also be used to publish Open Graph actions. It is generated using a pre-agreed secret between the app and Facebook and is then used during calls that change app-wide settings. You obtain an app access token via a server-to-server call. |
|
These access tokens are similar to user access tokens, except that they provide permission to APIs that read, write or modify the data belonging to a Facebook Page. To obtain a page access token you need to start by obtaining a user access token and asking for the |
|
Client Token |
The client token is an identifier that you can embed into native mobile binaries or desktop apps to identify your app. The client token isn't meant to be a secret identifier because it's embedded in apps. The client token is used to access app-level APIs, but only a very limited subset. The client token is found in your app's dashboard. Since the client token is used rarely, we won't talk about it in this document. Instead it's covered in any API documentation that uses the client token. |
Generating Access Tokens
- User Access Tokens
- App Access Tokens
- Page Access Tokens
User Access Tokens
Although each platform generates access tokens through different APIs,
all platforms follow the basic strategy to get a user token:
Different platforms have different methods to kick off this process and include functionality to manage access tokens on behalf of the developer and the person granting permissions:
Javascript
The Facebook SDK for Javascript obtains and persists user access tokens automatically in browser cookies. You can retrieve the user access token by making a call to FB.getAuthResponse
which will include an accessToken
property within the response.
FB.getLoginStatus(function(response) { if (response.status === 'connected') { var accessToken = response.authResponse.accessToken; } } );
Android
The Facebook SDKs for Android automatically manages user access tokens through the class com.facebook.AccessToken
. You can learn more about obtinaing a user access token by implementing Facebook Login for Android. You can retrieve the user access token by inspecting Session.getCurrentAccessToken
.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); accessToken = AccessToken.getCurrentAccessToken(); }
iOS
The Facebook SDKs for iOS automatically manages user access tokens through the class FBSDKAccessToken
. You can learn more about obtinaing a user access token by implementing Facebook Login for iOS. You can retrieve the access token by inspecting FBSDKAccessToken.currentAccessToken
.
- (void)viewDidLoad { [super viewDidLoad]; NSString *accessToken = [FBSDKAccessToken currentAccessToken]; }
Web (without JavaScript)
When building an app with on the web without Facebook's SDK for Javascript you will need to generate an access token during the steps outlined in that document.
Short-Term Tokens and Long-Term Tokens
User access tokens come in two forms: short-lived tokens and long-lived tokens.
Short-lived tokens usually have a lifetime of about an hour or two, while long-lived tokens usually have a lifetime of about 60 days.
You should not depend on these lifetimes remaining the same - the lifetime may change without warning or expire early. See more under handling errors.
Access tokens generated via web login are short-lived tokens, but you can convert them to long-lived tokens by making a server-side API call along with your app secret.
Mobile apps that use Facebook's iOS and Android SDKs get long-lived tokens by default.
Apps with Standard access to Facebook's Marketing API when using long-lived tokens will receive long-lived tokens that don't have an expiry time.
These tokens are still subject to invalidation for other reasons, but won't expire solely based on time. This is also true of access tokens for System Users in Business Manager.
Tokens are Portable
One important aspect to understand about access token is that they are portable.
Once you have an access token you can use it to make calls from a mobile client, a web browser, or from your server to Facebook's servers.
- If a token is obtained on a client, you can ship that token down to your server and use it in server-to-server calls.
- If a token is obtained via a server call, you can also ship that token up to a client and then make the calls from the client.
Moving tokens between your client and server must be done securely over HTTPS to ensure the security of people's accounts.
Read more about the implications of moving tokens between your clients and your server.
App Access Tokens
App access tokens are used to make requests to Facebook APIs on behalf of an app rather than a user.
This can be used to modify the parameters of your app, create and manage test users, or read your apps's insights.
Limitations
Some user data that would normally be visible to an app that's making a request with a user access token isn't always visible with an app access token.
If you're reading user data and using it in your app, you should use a user access token instead of an app access token.
App access tokens are considered insecure if your app is set to Native/Desktop
in the Advanced settings of your App Dashboard and therefore will not work with API calls. This is because we assume that native or desktop apps will have the app secret embedded somewhere (and therefore the app access token generated using that secret is not secure).
Generating an App Access Token
To generate an app access token, you need to make a Graph API call:
GET /oauth/access_token ?client_id={app-id} &client_secret={app-secret} &grant_type=client_credentials
This call will return an app access token which can be used in place of a user access token to make API calls as noted above.
Again, for security, app access token should never be hard-coded into client-side code, doing so would give everyone who loaded your webpage or decompiled your app full access to your app secret, and therefore the ability to modify your app.
This implies that most of the time, you will be using app access tokens only in server to server calls.
Note that because this request uses your app secret, it must never be made in client-side code or in an app binary that could be decompiled.
It is important that your app secret is never shared with anyone. Therefore, this API call should only be made using server-side code.
There is another method to make calls to the Graph API that doesn't require using a generated app access token.
You can just pass your app id and app secret as the access_token
parameter when you make a call:
https://graph.facebook.com/endpoint?key=value&access_token=app_id|app_secret
The choice to use a generated access token vs. this method depends on where you hide your app secret.
Page Access Tokens
Page access tokens are used in Graph API calls to manage Facebook Pages.
To generate a page access token, an admin of the page must grant an extended permission called manage_pages
.
Once this permission has been granted, you can retrieve the page access token using a user access token with the required permissions and the following Graph API request:
GET /me/accounts HTTP/1.1 Host: graph.facebook.com
This returns a list of pages that the person administers along with other information about the Page, such as the Page category, the permissions the admin has for that Page, and the page access token:
{ "data": [ { "category": "Product/service", "name": "Sample Page", "access_token": "{access-token}", "id": "1234567890", "perms": [ "ADMINISTER", "EDIT_PROFILE", "CREATE_CONTENT", "MODERATE_CONTENT", "CREATE_ADS", "BASIC_ADMIN" ] }, }
With a page access token you can make API calls on behalf of a Page.
For example, you could post a status update to a Page (rather than on the user's timeline) or read Page Insights data.
Page access tokens are unique to each Page, admin, and app.
Page admins have different roles, which are indicated by the returned perms
array, as in the example above.
The functionality available to them is decided based on the perms
values, which are described in Tokens & Roles.
Advanced Topics
Using Tokens with different App Types
Manually Build a Login Flow
The easiest and quickest way to implement Facebook Login is with our official SDKs for JavaScript, iOS, and Android.
We recommend you follow our separate guides for these platforms.
However, if you need to implement browser-based login for an app without using our SDKs, such as in a webview for a native desktop app (for example Windows 8), or a login flow using entirely server-side code, you can build a Login flow for yourself by using browser redirects.
This guide will take you through each step of the login flow and show you how to implement each one without using our SDKs:
- Checking login status
- Logging people in
- Confirming identity
- Storing access tokens and login status
- Logging people out
To use Facebook Login in a desktop app, you'll need to be able to embed a web browser (sometimes called a webview) within the app to perform the login process.
Checking Login Status
Apps using our SDKs can check whether someone has already logged in using built-in functions.
All other apps must create their own way of storing when a person has logged in, and when that indicator is not there, proceed on the assumption that they are logged out.
If someone is logged out, then your app should redirect them to the Login dialog at an appropriate time — for example if they click a login button.
Logging People In
Whether someone is not logged into your app or not logged into Facebook, you can use the Login dialog to prompt them to do both.
If they aren't logged into Facebook, they'll be prompted to login and then move onto logging into your app.
This is automatically detected, so you don't need to do anything extra to enable this behavior.
Invoking the Login Dialog and Setting the Redirect URL
Your app must initiate a redirect to an endpoint which will display the login dialog:
https://www.facebook.com/v2.12/dialog/oauth? client_id={app-id} &redirect_uri={redirect-uri} &state={state-param}
This endpoint has the following required parameters:
client_id
. The ID of your app, found in your app's dashboard.redirect_uri
. The URL that you want to redirect the person logging in back to. This URL will capture the response from the Login Dialog. If you are using this in a webview within a desktop app, this must be set tohttps://www.facebook.com/connect/login_success.html
. You can confirm that this URL is set for your app in the App Dashboard. Under Products in the App Dashboard's left side navigation menu, click Facebook Login, then click Settings. Verify the Valid OAuth redirect URIs in the Client OAuth Settings section.state
. A string value created by your app to maintain state between the request and callback. This parameter should be used for preventing Cross-site Request Forgery and will be passed back to you, unchanged, in your redirect URI.
#For example, if your login request looks like: https://www.facebook.com/v2.12/dialog/oauth? client_id={app-id} &redirect_uri={"https://www.domain.com/login"} &state={"{st=state123abc,ds=123456789}"} #then your redirect URI would be called with this: https://www.domain.com/login?state="{st=state123abc,ds=123456789}"
It also has the following optional parameters:
response_type
. Determines whether the response data included when the redirect back to the app occurs is in URL parameters or fragments. See the Confirming Identity section to choose which type your app should use. This can be one of:code
. Response data is included as URL parameters and containscode
parameter (an encrypted string unique to each login request). This is the default behavior if this parameter is not specified. It's most useful when your server will be handling the token.token
. Response data is included as a URL fragment and contains an access token. Desktop apps must use this setting forresponse_type
. This is most useful when the client will be handling the token.code%20token
. Response data is included as a URL fragment and contains both an access token and thecode
parameter.granted_scopes
. Returns a comma-separated list of all Permissions granted to the app by the user at the time of login. Can be combined with otherresponse_type
values. When combined withtoken
, response data is included as a URL fragment, otherwise included as a URL parameter.
scope
. A comma or space separated list of Permissions to request from the person using your app.
For Windows 8 Apps
If you are building Login for a Windows app you can use the Package Security Identifier as your redirect_uri
.
Trigger the Login Dialog by calling WebAuthenticationBroker.AuthenticateAsync
and use the Login Dialog endpoint as the requestUri. Here is an example in JavaScript:
var requestUri = new Windows.Foundation.Uri( "https://www.facebook.com/v2.12/dialog/oauth? client_id={app-id} &display=popup &response_type=token &redirect_uri=ms-app://{package-security-identifier}"); Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync( options, requestUri) .done(function (result) { // Handle the response from the Login Dialog } );
This will return control flow back to your app with an access token on success, or error on failure.
Handling Login Dialog Response
At this point in the login flow, the person will see the Login dialog and will have a choice of whether to cancel or to let the app access their data.
If the person using the app chooses OK on the Login dialog, they grant access to their public profile, friend list and any additional Permissions your app requested.
In all cases, the browser returns to the app, and response data indicating whether someone connected or cancelled is included. When your app uses the redirect method as above, the redirect_uri
your app returns to will be appended with URL parameters or fragments (as per the chosen response_type
), which must be captured.
Because of the various combinations of code languages that could be used in web apps, our guide doesn't show specific examples. However most modern languages will be capable of URL parsing, as follows:
- Client-side JavaScript can capture URL fragments (for example jQuery BBQ), whereas URL parameters can be captured by both client-side and server-side code (for example
$_GET
in PHP,jQuery.deparam
in jQuery BBQ,querystring.parse
in Node.js orurlparse
in Python). - Microsoft provides a guide and sample code for Windows 8 apps connecting to an "online provider" - in this case, Facebook.
When using a desktop app and logging in, Facebook redirects people to the redirect_uri
mentioned above and places an access token along with some other metadata (such as token expiry time) in the URI fragment:
https://www.facebook.com/connect/login_success.html# access_token=ACCESS_TOKEN...
Your app needs to detect this redirect and then read the access token out of the URI using the mechanisms provided by the OS and development framework you are using.
You can then skip straight to the Inspecting access tokens step.
Canceled Login
If people using your app don't accept the Login dialog and clicks Cancel, they'll be redirected to the following:
YOUR_REDIRECT_URI? error_reason=user_denied &error=access_denied &error_description=Permissions+error.
See Handling Missing Permissions for more about what apps should do when people refuse to login.
Confirming Identity
Because this redirect flow involves browsers being redirected to URLs in your app from the Login dialog, traffic could directly access this URL with made-up fragments or parameters.
If your app assumed these were valid parameters, the made-up data would be used by your app for potentially malicious purposes.
As a result, your app should confirm that the person using the app is the same person that you have response data for before generating an access token for them.
Confirming identity is accomplished in different ways depending on the response_type
received above:
- When
code
is received, it has to be exchanged for an access token using an endpoint. The call will need to be server-to-server, since it involves your app secret. (Your app secret should never end up in client code.) - When
token
is received, it needs to be verified. You should make an API call to an inspection endpoint that will indicate who the token was generated for and by which app. As this API call requires using an app access token, never make this call from a client. Instead make this call from a server where you can securely store your app secret. - When
code
andtoken
are both received, both steps should be performed.
Note that you can also generate your own state
parameter and use it with your login request to provide CSRF protection.
Exchanging Code for an Access Token
To get an access token, make an HTTP GET request to the following OAuth endpoint:
GET https://graph.facebook.com/v2.12/oauth/access_token? client_id={app-id} &redirect_uri={redirect-uri} &client_secret={app-secret} &code={code-parameter}
This endpoint has some required parameters:
client_id
. Your app's IDsredirect_uri
. This argument is required and must be the same as the originalrequest_uri
that you used when starting the OAuth login process.client_secret
. Your unique app secret, shown on the App Dashboard. This app secret should never be included in client-side code or in binaries that could be decompiled. It is extremely important that it remains completely secret as it is the core of the security of your app and all the people using it.code
. The parameter received from the Login Dialog redirect above.
Note: From v2.3 onward this endpoint will return a proper JSON response. If your call doesn't specify a version it will default to the oldest available version.
Response
The response you will receive from this endpoint will be returned in JSON format and, if successful, is:
{ "access_token": {access-token}, "token_type": {type}, "expires_in": {seconds-til-expiration} }
If it is not successful, you will receive an explanatory error message.
Inspecting Access Tokens
Whether or not your app uses code
or token
as your response_type
from the Login dialog, it will have received an access token.
You can perform automated checks on these tokens using a Graph API endpoint:
GET graph.facebook.com/debug_token? input_token={token-to-inspect} &access_token={app-token-or-admin-token}
This endpoint takes the following parameters:
input_token
. The token you need to inspect.access_token
An app access token or an access token for a developer of the app.
The response of the API call is a JSON array containing data about the inspected token. For example:
{ "data": { "app_id": 138483919580948, "type": "USER", "application": "Social Cafe", "expires_at": 1352419328, "is_valid": true, "issued_at": 1347235328, "metadata": { "sso": "iphone-safari" }, "scopes": [ "email", "publish_actions" ], "user_id": "1207059" } }
The app_id
and user_id
fields help your app verify that the access token is valid for the person and for your app.
For a full description of the other fields, see the Getting Info about Access Tokens guide.
Checking Permissions
The /me/permissions
edge can be called in order to retrieve a list of permissions that have been granted or declined by a particular user. Your app can use this to check which of the requested permissions it cannot use for any particular user.
Re-asking for Declined Permissions
Facebook Login lets people decline sharing some permissions with your app. The Login Dialog contains a screen that looks like this:
The public_profile
permission is always required and greyed out because it can't be disabled.
However, if someone were to uncheck user_likes
(Likes) in this example, checking /me/permissions
for which permissions have been granted results in:
{ "data": [ { "permission":"public_profile", "status":"granted" }, { "permission":"user_likes", "status":"declined" } ] }
Note that user_likes
has been declined instead of granted.
It's OK to ask a person again to grant your app permissions that they've declined.
You should have a screen of education on why you think they should grant the permission to you and then re-ask.
But if you invoke the Login Dialog as before, it won't ask for that permission.
This is because once someone has declined a permission, the Login Dialog will not re-ask them for it unless you explicitly tell the dialog you're re-asking for a declined permission.
You do this by adding the auth_type=rerequest
parameter to your Login Dialog URL:
https://www.facebook.com/v2.12/dialog/oauth? client_id={app-id} &redirect_uri={redirect-uri} &auth_type=rerequest scope=email
Using this, the Login Dialog will re-ask for the declined permission.
Storing Access Tokens and Login Status
At this point in the flow, you have someone authenticated and logged in. Your app is ready to make API calls on their behalf. Before doing so, it should store the access token and the login status of the person using the app.
Storing Access Tokens
After your app receives the access token from the previous step, the token should be stored so it's available to all parts of the app when it makes API calls.
- There is no specific process here, however in general if you're building a web app, it is best to add the token as a session variable to identify that browser session with a particular person,
- if you're building a native desktop or mobile app, then you should use the datastore available to your app. Also, the app should store the token in a database along with the
user_id
to identify it.
Please see our note about the size of access tokens in the access token document.
Tracking login status
Again, your app should store a person's login status, which helps avoid having to make additional calls to the Login dialog. Whatever procedure you chose, modify your login status checking to account for it.
Logging People Out
You can log people out of your app by undoing whatever login status indicator you added,
for example deleting the session that indicates a person is logged in.
You should also remove the stored access token.
Logging someone out is not the same as revoking login permission (removing previously granted authentication), which can be performed separately. Because of this, build your app so it doesn't automatically force people who have logged out back to the Login dialog.
Detecting When People Uninstall Apps
People are able to uninstall apps via Facebook.com without interacting with the app itself. To help apps detect when this has happened, we allow them to provide a de-authorize callback URL which will be pinged whenever this occurs.
You can enable a deauthorize callback through the App Dashboard. Just go to your app, then choose the Products, then Facebook Login, and finally Settings. A text field is provided for the Deauthorize Callback URL.
Whenever a user of your app de-authorizes it, this URL will be sent an HTTP POST
containing a signed request. Read our guide to parsing the signed request to see how to decode this to find out the user ID that triggered the callback.
Facebook Login Best Practices
The onboarding experience is one of the most important user experiences in your app.
Facebook Login lets people start using your app quickly and easily, and they'll enjoy more personalized and meaningful experiences.
In this doc, we offer some tips and considerations to optimize your login flow. A high quality onboarding experience can lead to conversion rates above 80%.
- Prompt people to log in at the right time.
- Only ask for the permissions you need.
- Ask for permissions in context and explain why.
- Use the button that comes with our SDKs.
- Avoid having people login from a WebView.
- Provide a way to log out.
- Test and measure.
- Follow the Facebook Platform Policy.
- Submit your app for Login Review.
Best Practices
1. Prompt people to log in at the right time
If your app is well known and understood, you might be able to put your login button on the initial screen and still see decent conversion rates. If you do this, be sure the intro screen has a clear, succinct and compelling statement about what it has to offer:
A better option is to provide a glimpse of the content available to people prior to logging in, like the background photo in this example:
If your app requires additional education, you may want to offer a multi step demo above your login button. This gives people the option to either log in immediately or learn more first.
The best experience is to let people use your app and see its content before prompting them to log in. For example, many ecommerce sites such as Zulily don't require people to log in until they're ready to check out.
2. Only ask for the permissions you need
Only ask for the permissions you need. The fewer permissions you ask for, the easier it is for people to feel comfortable granting them. We've seen that asking for fewer permissions typically results in greater conversion.
You can always ask for additional permissions later after people have had a chance to try out your app.
An additional benefit of asking for fewer permissions is that you might not need to submit your app for Login Review. You need to submit for Login Review if you request any permissions other than public_profile
and email
.
3. Ask for permissions in context and explain why
You should trigger permission requests when people are trying to accomplish an action in your app which requires that specific permission.
For example, the Facebook app only asks for Location Services when people explicitly tap on the location button when updating their status.
Asking for permissions in context is especially important when your app is asking for publish permissions. We recommend that you ask for publish permissions after people click a share, post, or publish option in your app. If your app only needs basic sharing functionality (e.g., sharing one item at a time, no custom composer), you can use our share dialog for iOS and Android.
In addition, people are most likely to accept permission requests when they clearly understand why your app needs that info to offer a better experience.
4. Use the button that comes with our SDKs
The Facebook Login button that comes with our SDKs is easy to integrate and includes built-in education that ensures a consistent design and experience:
However, if you do decide to build your own, for best results follow the Facebook Platform Policy and the recommendations in the User Experience Design topic.
5. Avoid having people login from a WebView
Logging in from a WebView works only if people have the Facebook app installed on their mobile device. Because you cannot predict whether people will have the app installed, it's better not to have them log in from a WebView.
6. Provide a way to log out
Once people are logged in, you should also give them a way to log out, disconnect their account, or delete it all together. In addition to being a courtesy, this is also a requirement of our Facebook Platform Policy.
The dating app Tinder, for example, gives you the option to log out or to delete your account entirely.
7. Test and measure
It's incredibly important to test your Facebook Login flow under a variety of conditions, and we've built a robust testing plan for you to follow.
It's also a good idea to run qualitative usability tests to understand how people are reacting to what they see.
Once you've tested your Login flow and are ready to launch, we suggest using an analytics program to understand if people are completing the process and their overall conversion rates. Best practice apps can see conversion rates of over 80%.
Facebook Analytics lets you monitor your conversion rates for free.
8. Follow the Facebook Platform Policy
To avoid potential problems later on, do a quick check to make sure your Login integration adheres to the login section of our policies.
9. Submit your app for Login Review
You only need to submit your app for Login Review if you're requesting permissions beyond public profile
and email
.
We recommend you submit your app for review as early as possible in your development lifecycle after you've integrated Facebook Login.
You'll receive transparent feedback during the Login Review process, including feedback on changes you can make to get a denied permission approved, if appropriate.
For existing apps, going through Login Review will not affect your current app.
You can learn more about Login Review in our docs.
Expiration and Extension of Access Tokens
Facebook's official SDKs manage the lifetime of tokens for you.
When using iOS, Android, or our JavaScript SDK, the SDK will handle making sure that tokens are refreshed before they expire.
Native mobile apps using Facebook's SDKs will get long-lived access tokens, good for about 60 days.
These tokens will be refreshed once per day when the person using your app makes a request to Facebook's servers.
If no requests are made, the token will expire after about 60 days and the person will have to go through the login flow again to get a new token.
Access tokens on the web often have a lifetime of about two hours, but will automatically be refreshed when required.
If you want to use access tokens for longer-lived web apps, especially server side, you need to generate a long-lived token.
A long-lived token generally lasts about 60 days.
This is what the process for generating a long-lived token looks like:
How to generate a long-lived token:
- Start with a short-lived token generated on a client and ship it back to your server.
- Use the user token, your app ID and app secret to make the following call from your server to Facebook's servers:
GET /oauth/access_token? grant_type=fb_exchange_token& client_id={app-id}& client_secret={app-secret}& fb_exchange_token={short-lived-token}
Make this call from your server, not a client.
The app secret is included in this API call, so you should never actually make the request client-side.
Instead implement server-side code that makes the request, then pass the response containing the long-lived token back to your client-side code.
This will be a different string than the original token, so if you're storing these tokens, replace the old one.
Once you've retrieved the long-lived token, you can use it from your server or ship it back down to the client to use there.
An important note: Apps are unable to exchange an expired short-lived token for a long-lived token. The flow above only works with short-lived tokens that are still valid. Once they expire, your app must send the user through the login flow again to generate a new short-lived token.
Refreshing Long-Lived Tokens
Even the long-lived access token will eventually expire. At any point, you can generate a new long-lived token by sending the person back to the login flow used by your web app -
note that the person will not actually need to login again, they have already authorized your app, so they will immediately redirect back to your app from the login flow with a refreshed token -
how this appears to the person will vary based on the type of login flow that you are using, for example
- if you are using the JavaScript SDK, this will take place in the background,
- if you are using a server-side flow, the browser will quickly redirect to the Login Dialog and then automatically and immediately back to your app again.
After doing the above you will obtain a new short-lived token and then you need to perform the same exchange for a long-lived token as above.
In some cases, this newer long-lived token might be identical to the previous one, but we can't guarantee it and your app shouldn't depend upon it.
With the iOS and Android SDKs, long-lived tokens are used by default and should automatically be refreshed.
Extending Page Access Tokens
Apps can retrieve a page access token from Page admin users when they authenticate with the manage_pages permission.
- If the user access token used to retrieve this page access token is short-lived, the page access token will also be short-lived.
- To get a longer-lived page access token, exchange the User access token for a long-lived one, as above, and then request the Page access token. The resulting page access token will not have any expiry time.
Using Long-Lived Tokens on Web Clients
You should, in general, not use the same long-lived tokens on more than one web client (i.e. if the person logs in from more than one computer.)
Instead you should use the long-lived tokens on your server to generate a code and then use that to get a long-lived token on the client.
Please see below for information Generating long-lived tokens from server-side long-lived tokens.
Generating Long-Lived User Tokens from Server-Side Long-Lived Tokens
Facebook has an advanced option for obtaining long-lived access tokens for apps that:
- Have their own authentication system (using a username/password for example)
- Store, on their servers, a Facebook access token for people using it that they send to different clients (browser or native mobile apps)
- Make API calls from all of those clients
If your app is set up like this it should use the process described here to obtain an access token from each client to avoid triggering Facebook's automated spam systems.
The end result will be that each client will have its own long-lived access token.
At a high level, this is how you can obtain a long-lived token from the client:
- Make a call to Facebook's server from your server using a valid and current long-lived token to generate a code. (This assumes you've already obtained a long-lived token via Facebook Login. If the token you're using is invalid or expired, you'll have to obtain a new one by making the person using your app log in again.)
- Securely send that code to the client.
- The client then exchanges the code for a long-lived token.
- The client can use the long-lived token to post stories or query data.
This is a diagram of the flow:
Getting the code
Using a long-lived user access token, make a call to the following endpoint:
https://graph.facebook.com/oauth/client_code?access_token=...&client_secret=...&redirect_uri=...&client_id=...
The call requires the following arguments:
Argument | Required | Description |
---|---|---|
|
Yes |
Long-lived user access token. |
|
Yes |
The App ID. |
|
Yes |
The app's app secret. |
|
Yes |
The redirect URI must be set to the exact value in the app's configuration. |
The response will look something like:
{"code": "...."}
Redeeming the code for an access token
Once you've retrieved the code from Facebook's server you then need to ship it to the client via a secure channel. Once that's done, you need to make a request from the client to this endpoint:
https://graph.facebook.com/oauth/access_token?code=...&client_id=...&redirect_uri=...&machine_id= ...
The call requires the following arguments:
Argument | Required | Description |
---|---|---|
|
Yes |
The App ID. |
|
Yes |
The code returned from Facebook's server. |
|
Yes |
The redirect URI must be set to the exact value in the app's configuration. |
|
No |
An important per-client (not per-user) value that tracks clients and is used for security. If you're previously made calls to get a code and been provided a |
The response will look like:
{"access_token":"...", "expires_in":..., "machine_id":"..."}
Returned values are:
Value | Description |
---|---|
|
A new long-lived access token that you can use for Graph API calls. |
|
The number of seconds until this access token expires. |
|
The machine_id for this client. Please store this for future calls to generate a new access token from a code. This helps identify this client and is used to prevent spam. |