Is there a way to check if Facebook access token is still valid?
Asked Answered
A

10

76

My site utilizes lifetime access tokens (offline_access). However, if the user changes his/her password, the access token gets reset. Is there a method to check if the current access token is valid before making calls to the Graph API? Thanks for your time.

Asir answered 2/10, 2010 at 9:35 Comment(1)
None of the answers posted here worked for me. However, this answer did: https://mcmap.net/q/245453/-how-would-you-perform-debug_token-call-using-facebook-php-sdkPolyhydric
C
41

Basically, FB wants you to poll for it, or to detect the case and redirect the user to get a reauth to occur. Annoying, but official:

(Old, out of date link. See below) https://developers.facebook.com/blog/post/500/

Edit: Facebook changed their link structure without redirects. Not surprised.

https://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/

Christopherchristopherso answered 15/6, 2011 at 19:36 Comment(3)
Sorry, the link you followed may be broken, or the page may have been removed.Forb
+1 for the "Not surprised" comment. :) "Move fast and break things" might be an awesome philosophy for Facebook corporate, but it sure makes our lives difficult...Devastate
@Devastate you stole my comment! I too like this answer for the "Not surprised" part. I hate FB. It's a real pain. :|Depolarize
S
75

Offline, without sending anything to facebook - I don't think so. The easiest way is probably to send a request to:

https://graph.facebook.com/me?access_token=...

Facebook also supports subscriptions for real-time updates, but I am not sure how to apply them to this situation.

Spaghetti answered 2/10, 2010 at 15:20 Comment(0)
B
48

If you want to know the token expiry time you can pass a open graph url using appid and token as below it will work .

https://graph.facebook.com/oauth/access_token_info?client_id=APPID&access_token=xxxxxxxxx
Blim answered 7/2, 2013 at 7:14 Comment(1)
The client_id parameter here does nothing. You can leave it out.Prana
C
41

Basically, FB wants you to poll for it, or to detect the case and redirect the user to get a reauth to occur. Annoying, but official:

(Old, out of date link. See below) https://developers.facebook.com/blog/post/500/

Edit: Facebook changed their link structure without redirects. Not surprised.

https://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/

Christopherchristopherso answered 15/6, 2011 at 19:36 Comment(3)
Sorry, the link you followed may be broken, or the page may have been removed.Forb
+1 for the "Not surprised" comment. :) "Move fast and break things" might be an awesome philosophy for Facebook corporate, but it sure makes our lives difficult...Devastate
@Devastate you stole my comment! I too like this answer for the "Not surprised" part. I hate FB. It's a real pain. :|Depolarize
F
7

You can check the token using the token debug service , take a look here

https://graph.facebook.com/debug_token?input_token=INPUT_TOKEN&access_token=ACCESS_TOKEN

https://developers.facebook.com/docs/howtos/login/debugging-access-tokens/

Fireball answered 10/4, 2013 at 13:48 Comment(2)
Although Chaitanya Bharat's answer is simpler and works well in most cases this approach seems to be the best for me.Zippy
What is an input token?Manado
B
4

The real time updates would allow you to solve this problem, but it would be pretty complicated. Basically, you can subscribe to updates that will tell you 1) if the user removed the app or 2) if the user removed permissions. You could use this to store the current permissions of the faceboook user. This way, if the user removed your app you would know that the access token is expired.

Real time updates is actually facebooks recommended way of handling permissions. Many apps make api calls every time a page is loaded to check for permissions. This tends to be slow and unreliable.

Britton answered 5/10, 2010 at 6:4 Comment(1)
What about when the user changes their password?Kristof
M
4

I went through these posts, bud I found very good solutions like this:

GET graph.facebook.com/debug_token?
    input_token={token-to-inspect}
    &access_token={app_id}|{app_secret}

Response from this request provides you everything you need:

  • your app ID - this verifies that token is from your application
  • application name - which can be also checked
  • expires_at - token expiration time
  • is_valid - boolean for check up
  • user_id - which you can also compare and check

Just note that "|" sign must be there as a letter

Marchak answered 25/1, 2018 at 22:35 Comment(0)
F
1
        //When user access token expires user must be logged in and renew the access token him self.it is a Facebook policy 
        //you can overcome this by sending email to users who have expired access token.
        //create a table of successful sending to monitor sending process
        //if any failure happened with the user an email is sent to him to ask him to activate there account again.with a link to your subscription page.
        //and here is the code should be written on that page. 
         $app_id = "YOUR_APP_ID";
         $app_secret = "YOUR_APP_SECRET"; 
         $my_url = "YOUR_POST_LOGIN_URL";

        // known valid access token stored in a database 
        $access_token = "YOUR_STORED_ACCESS_TOKEN";

        $code = $_REQUEST["code"];

       // If we get a code, it means that we have re-authed the user 
       //and can get a valid access_token. 
       if (isset($code)) {
         $token_url="https://graph.facebook.com/oauth/access_token?client_id="
           . $app_id . "&redirect_uri=" . urlencode($my_url) 
           . "&client_secret=" . $app_secret 
           . "&code=" . $code . "&display=popup";
         $response = file_get_contents($token_url);
         $params = null;
         parse_str($response, $params);
         $access_token = $params['access_token'];
       }


       // Attempt to query the graph:
       $graph_url = "https://graph.facebook.com/me?"
         . "access_token=" . $access_token;
       $response = curl_get_file_contents($graph_url);
       $decoded_response = json_decode($response);

       //Check for errors 
       if ($decoded_response->error) {
       // check to see if this is an oAuth error:
         if ($decoded_response->error->type== "OAuthException") {
           // Retrieving a valid access token. 
           $dialog_url= "https://www.facebook.com/dialog/oauth?"
             . "client_id=" . $app_id 
             . "&redirect_uri=" . urlencode($my_url);
           echo("<script> top.location.href='" . $dialog_url 
          . "'</script>");
        }
        else {
          echo "other error has happened";
        }
      } 
      else {
      // success
        echo("success" . $decoded_response->name);
        echo($access_token);
      }

      // note this wrapper function exists in order to circumvent PHP's 
      //strict obeying of HTTP error codes.  In this case, Facebook 
      //returns error code 400 which PHP obeys and wipes out 
      //the response.
      function curl_get_file_contents($URL) {
        $c = curl_init();
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($c, CURLOPT_URL, $URL);
        $contents = curl_exec($c);
        $err  = curl_getinfo($c,CURLINFO_HTTP_CODE);
        curl_close($c);
        if ($contents) return $contents;
        else return FALSE;
      }
Forb answered 10/6, 2013 at 14:30 Comment(0)
G
1

Offline - it is not possible

Ask that user has given permission or not:

https://graph.facebook.com/{facebook-id}/permissions?access_token={access-token}

If access token is invalid then it will give error:

{  
   error:{  
      message:"The access token could not be decrypted",
      type:"OAuthException",
      code:190
   }
}

Otherwise it will give list of permission that user has given:

data:[  
   {  
      installed:1,
      ...... permission list......... 
      bookmarked:1
   }
]
Goss answered 27/12, 2014 at 7:59 Comment(0)
K
0

Updating this as things have changed since OP:

You can debug access tokens here: https://developers.facebook.com/tools/debug/accesstoken?version=v2.5&q={access_token}

Kenward answered 16/10, 2015 at 21:4 Comment(0)
M
-6

Otto's answer of the facebook post seems to be the official response on this question, however it uses straight PHP instead of the SDK and also uses JS to resolve the issue instead of PHP. If you are using PHP to check for a valid session you often need a PHP method of ensuring a valid session in order to continue.

The following code checks for the me object with the graph API. If an exception is thrown it destroys* the current Facebook session.

try{
    $facebook->api('/me');
}
catch( FacebookApiException $e ){
    $facebook->destroySession();
}

This forces later graph calls to instantiate a new Facebook session. This at least gives you access to public data so that you can render pages do not require FB user permissions:

$facebook->api('/userName');

To reobtain user permission access the user will need to login to your app (this is distinct from being logged into Facebook itself). You can do this with JS or with PHP:

$facebook->getLoginUrl();

*Note the destroySession() call is not in a tagged release of the PHP SDK yet. Use the master branch or patch it in.

Memorialist answered 24/1, 2012 at 1:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.