Storing a user's Facebook access token
I have a database that stores a user's access token (along with some other data). My list of permissions include offline_access when I authorize the user.
So will the user's access token (client side) always be the same as that user开发者_C百科's access token in the database? Or can the user's access token change when they log out, change their password, etc?
No, the access token will not always be the same, even with offline_access. You will need to get a new access token when 1) the user changes their password or 2) deactivates your app. Otherwise, it should remain the same.
The users Facebook id will never change though. This can be parsed from the access token or obtained by calling the /me graph api.
Facebook has a blog post that goes on in detail about this.
Update: Facebook added a blog post specifically for handling revoked authorization.
Just wanted to point out that the offline_access permission has been removed.
https://developers.facebook.com/roadmap/offline-access-removal/
"While we are removing the use of the offline_access permission, through a migration setting in the Developer App, we are now allowing the option to use access_tokens with a long-lived expiration time that can be renewed each time the user revists your app (see exceptions below)."
With more searching you will find how to extend the access token.
How to extend access token validity since offline_access deprecation
Here is a working example from https://stackoverflow.com/a/13224416/1753925:
$facebook->setExtendedAccessToken();
$access_token = $_SESSION["fb_".$fb_appId."_access_token"];
// now set it into the facebook object ....
$facebook->setAccessToken($access_token);
// now our fb object will use the new token as usual ...
$accessToken = $facebook->getAccessToken();
<?php
# We require the library
require("facebook.php");
require("db.php");
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET_ID',
'cookie' => true
));
# Let's see if we have an active session
$session = $facebook->getSession();
if(!empty($session))
{
try
{
$facebook_id = $session['uid'];
$facebook_access_token=$session['access_token'];
// Updating Facebook values into Users table
mysql_query("UPDATE users SET facebook_uid='$facebook_id', facebook_access_token='$facebook_access_token' WHERE username='$user_session'");
header("Location: http://yourwebsite.com/home.php");
}
catch (Exception $e){}
}
else
{
header("Location: http://yourwebsite.com/home.php");
}
Not always.
Access tokens normally will expire after some point in time. There is a way to make an access token with an infinite expire time though, but you need to request for offline_access
as one of the permissions.
Look here for more information.
Edit Just saw that you require offline_access as a permission. Then no, they will not expire
精彩评论