56

I have managed to post to Facebook Page via API (C#), but when administrator of the page logs out, the following error occurs:

"(OAuthException - #190) Error validating access token: The session is invalid because the user logged out."

How do I generate access token which is never expired?

I need a solution that doesn't open Facebook Login dialog.

Gajus
  • 69,002
  • 70
  • 275
  • 438
Ivan Studenikin
  • 1,362
  • 4
  • 17
  • 30
  • possible duplicate of [Facebook Page Access Tokens - Do these expire?](http://stackoverflow.com/questions/7696372/facebook-page-access-tokens-do-these-expire) – Igy Jul 02 '13 at 19:37
  • You shoulda posted your solution as an answer, and then select it as answering your question :) Otherwise the question will preserve the "unanswered" status. – WindChimes Dec 22 '13 at 01:28
  • http://stackoverflow.com/questions/13953265/facebook-non-expiring-access-token#answer-19800733 (don't forget to have a fb page created) – paulalexandru Sep 18 '15 at 09:57
  • Possible duplicate of [facebook: permanent Page Access Token?](https://stackoverflow.com/questions/17197970/facebook-permanent-page-access-token) – vaultah Oct 02 '17 at 16:55

12 Answers12

31

You can generate never expiring access token without coding, following this instructions:

  1. Open graph Explorer: https://developers.facebook.com/tools/explorer/.
  2. Choose your application from the right corner dropdown.
  3. From "Get Token" dropdown choose your Fan Page.
  4. Click on submit button to generate token.
  5. From the left side on "Search for a field" enter access_token and click submit again. Copy this token from the main window.
  6. Open https://developers.facebook.com/tools/debug/accesstoken and paste token here. Click "Debug".
  7. Click the button "Extend Access Token". This will generate never expiring token.
Artem P
  • 5,198
  • 5
  • 40
  • 44
Mile Janev
  • 319
  • 1
  • 3
  • 2
23

This is the code that I use to generate "Never" expire access token using PHP SDK:

$facebook = new \Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.10',
  'default_access_token' => '{access-token}'
]);

// Exchange token
$token = $facebook->post('/oauth/access_token',
    array(  
        'grant_type' => 'fb_exchange_token',           
        'client_id' => 'APP ID',
        'client_secret' => 'APP Secret',
        'fb_exchange_token' => 'access Token'
    )
);
$token = $token->getDecodedBody();
$token = $token['access_token'];

echo $token;

I echo the access token and then debug it using the access token debugger. The result should be: Expires: Never.

References from the Documentation:

Maycow Moura
  • 6,471
  • 2
  • 22
  • 19
Ari
  • 4,643
  • 5
  • 36
  • 52
  • 3
    The only thing I can get with this metod is a token which expires in 2 months. Any idea? – mcont Sep 04 '14 at 16:00
  • 2
    Native mobile applications 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. from: https://developers.facebook.com/docs/facebook-login/access-tokens/#extending – Josejulio Oct 09 '14 at 21:11
  • 1
    [Someone did it better](http://stackoverflow.com/a/43349492/5040900). I got a never expire token with this code. – Siddhant Rimal Apr 17 '17 at 11:39
  • I see people using fb_exchange_token in order to get never expiring access tokens. But I'm receiving never expiring access tokens without having to use fb_exchange token. I let my user login via the auth dialog, which gives me a code. The code then gets plugged into endpoint /oauth/access_token (client_id, client_secret, redirect_uri, code), which gives me a user access token. I debug it, and it shows as never expiring. I then use the user access token in endpoint /{userId}/accounts (access_token, limit) and I get page access tokens. Debugging these reveals they never expire. V2.12. – Jay Mar 09 '18 at 15:16
11
  1. Generate long-lived token for admin of the fan page http://appdevresources.blogspot.sg/2012/11/extend-facebook-access-token-make-it.html (nice explanation with images)
  2. Generate long-lived token for fan page itself http://appdevresources.blogspot.sg/2012/11/retrieving-facebook-page-id-and.html
  3. Use token from 2) to post on the fan page's wall (no need for Facebook Login dialog)
  4. Resulted token will never expire (even if administrator of the fan page did log out)
Gajus
  • 69,002
  • 70
  • 275
  • 438
Ivan Studenikin
  • 1,362
  • 4
  • 17
  • 30
4

You can use following api from facebook to refresh token life to 60 days and just when the token is about to expire, call the same api again with-in 60 days to refresh its life back to 60 days from that point of time Token expire is present in expires parameter and its value is in seconds

Replace CLIENT_ID and CLIENT_SECRET with their actual value

https://graph.facebook.com/oauth/access_token?client_id=<CLIENT_ID>
&client_secret=<CLIENT_SECRET>&grant_type=fb_exchange_token
&fb_exchange_token=<ACCESS_TOKEN>

in ACCESS_TOKEN, put the actual token value without appending "access_token="

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
Harsh Gupta
  • 197
  • 6
  • Huhh?? Are you sure about that? Is it possible to extend the token life-time even if the user is not involved to confirm this extension? – Paul0515 Oct 17 '13 at 09:09
  • Remember to call this ONLY from server. Do not expose your `client_secret` to mobile or client side applications, this is major security flaw. – tomrozb Jun 21 '15 at 20:53
  • I'm not sure this is possible, at least not anymore, anytime i try to extend the token again it still shows a decreasing amount of time. – Michael Strobel Jul 30 '17 at 16:00
4
  1. Create an app if you don't have - https://developers.facebook.com/
  2. Create a short lived user access token in the Graph Explorer - https://developers.facebook.com/tools/explorer/

Select your app created above and select “Get user access token in the drop down”

In the user access token pop up you can select some permissions for the token. For an non expiry page access token you need to select "publish pages" and "manage pages"

  1. Create long lived user access token

Go to https://developers.facebook.com/tools/accesstoken/. There you will find short lived user access tokens and app access token of all the apps you have

Press debug option of user access token of the app created above. This will take you to the debug tool. Where you can find all the information of short lived user access token.

In the bottom there is option to generate long lived(60 days) user access token for this short lived user access token. Generate long lived user access token by selecting “Extend Access Token”

  1. Create never expired page access token

a. Go to the Graph Explorer - https://developers.facebook.com/tools/explorer/.

b. Paste the long lived user access token generated in previous step inside “Access token” field.

c. Access “/me?fields=access_token” api . This will result page access tokens and pages related to them. These page access tokens will never expire(until user change the password/user revoke the app)

  1. Verify non expiry page access token

a. Go to https://developers.facebook.com/tools/debug/accesstoken/

b. Add the page access token retrieved from above step into “Access token “ field and debug

You will get expires as Never

Found here with little changes: https://medium.com/@Jenananthan/how-to-create-non-expiry-facebook-page-token-6505c642d0b1

Madiddlta
  • 41
  • 2
3

It's November 2018 and this worked for me!

<?php
$args=[
    'usertoken'=>'xxx',
    'appid'=>'xxx',
    'appsecret'=>'xxx',
    'pageid'=>'xxx'
];
function generate_token($args){

$r = json_decode(file_get_contents("https://graph.facebook.com/v2.9/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
    $longtoken=$r->access_token;
    $r=json_decode(file_get_contents("https://graph.facebook.com/{$args['pageid']}?fields=access_token&access_token={$longtoken}")); // get user id
    $finaltoken=$r->access_token;
    return $finaltoken;
}
echo "https://graph.facebook.com/v2.9/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}";
echo '<br><br>Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';

Never Expire from FB Debug

Dazza
  • 126
  • 7
  • Can I do that without code ? I mean directly on Facebook API. – Tahola Dec 24 '18 at 14:23
  • 1
    Sure... Assuming you're starting from scratch... 1. Create Facebook App via the FB Developers site 2. Then replace APPID, APPSECRET, USERTOKEN, with those you just generated from above in the below URL... https://graph.facebook.com/v2.9/oauth/access_token?grant_type=fb_exchange_token&client_id=APPID&client_secret=APPSECRET&fb_exchange_token=USERTOKEN 3. Then grab the access token the above URL outputs... and replace it with ACCESSTOKEN in the below URL ... also adding your PAGEID from your FB Page. https://graph.facebook.com/PAGEID?fields=access_token&access_token=ACCESSTOKEN – Dazza Jan 01 '19 at 16:13
2

The accepted answer is no longer correct. This works now.

Open graph Explorer: https://developers.facebook.com

  • Login and choose your application from the right corner dropdown
  • Once logged in click Tools & Support icon in top right corner
  • Then choose Access Token Tool link on the right side beneath your applications name

To the right of the displayed user token > click [Debug] button

This will have taken you to the Access Token Debugger

  • Click the blue button at the bottom that says Extend Access Token
  • This will say: This new long-lived access token will never expire
  • Copy and paste that token into your application ie; EAAYMFDuobYUBADtYjVDukwBGpwPHOCY0iYglYY3j3r200MzyBZB4.....
Jay Lepore
  • 85
  • 1
  • 7
2

You need to get a user access token by FB.login() with manage_pages, pages_show_list and others in scope permissions. Then, execute FB.api("/{user-app-id}/accounts", fields: ...) to get a list of pages with their respectively info, including access_token. Here, you get a short-lived-token, but with this token you can extend its expiration time to "Never".

FB.login(function (response){
  if(response.status!=="connected"){
    return;
  }        
  FB.api('/'+USER_APP_ID+'/accounts',{fields: 'id, name, access_token,category, picture'}, 
   function(d){
    console.log(d) // Here you get access_token (short-lived-token)
  });
},{scope: 'manage_pages, pages_show_list', auth_type: 'rerequest'});

With the last access token and from server side, you make a call to API Graph, using App ID and App Secret of the App you use to get permissions to manage the page.

GET /oauth/access_token?  
grant_type=fb_exchange_token&           
client_id={app-id}&
client_secret={app-secret}&
fb_exchange_token={short-lived-token} 

The response gives you an access token with expiration time in "Never".

References: API Graph Accounts, Expiration and Extends Access Tokens

Harry Martel
  • 1,207
  • 8
  • 6
1

The method below worked for me, if you are using 4.x Facebook SDK:

  1. Create the Temporary User Access Token for the first time using the method mentioned here.
  2. Now! It's time to convert this token to Long Term Token using PHP SDK 4.x. Use the following code as it worked for me:

//Class for Generating the Long Lived Token

namespace App\Lib;

use Facebook\FacebookApp;
use Facebook\FacebookClient;
use Facebook\Authentication\OAuth2Client;

class FacebookLongLivedTokenGenerator
{
    public $longLivedTokenGenerated = false;

    public function generateFacebookLongLivedToken($appId, $appSecret, $oldToken)
    {
        //request new access token
        $oauth2Fb = new OAuth2Client(new FacebookApp($appId, $appSecret), new FacebookClient());
        $longLivedToken = $oauth2Fb->getLongLivedAccessToken($oldToken);
        if ($longLivedToken) {
            $this->longLivedTokenGenerated = true;
            $this->userAccessToken = $longLivedToken;
        }
        return trim($this->userAccessToken);
    }
}

You can consume the above class this way:

$longToken = new FacebookLongLivedTokenGenerator();
echo $longToken->generateFacebookLongLivedToken($appId, $appSecret, $oldUserAccessToken);
Community
  • 1
  • 1
Imran Zahoor
  • 2,521
  • 1
  • 28
  • 38
0

this Makefile works as of 2015-10-29. steps 2 and 3 give only a two-month token, but the page access token given in the final step shows in the debugger as "Expires: Never". this answer draws upon the work of several others, and is provided in the hopes that it will simplify things for developers regardless of preferred programming language.

before using this, you need to put your existing page ID, app ID, and app secret, in that order, in your ~/.netrc file as follows: machine graph.facebook.com login 123456 account 234567 password 345678

also before using this, login to Facebook with w3m, clicking "Keep me logged in".

MACHINE := graph.facebook.com
PAGE_ID := $(shell awk '$$2 ~ /^$(MACHINE)$$/ {print $$4}' $(HOME)/.netrc)
APP_ID := $(shell awk '$$2 ~ /^$(MACHINE)$$/ {print $$6}' $(HOME)/.netrc)
APP_SECRET := $(shell awk '$$2 ~ /^$(MACHINE)$$/ {print $$8}' $(HOME)/.netrc)
PERMISSIONS := manage_pages,publish_actions,publish_pages
FB := https://www.facebook.com
GRAPH := https://$(MACHINE)
CODE ?=
TOKEN ?=
TWOMONTHTOKEN ?=
BROWSER ?= w3m -dump
REDIRECT := http://jc.unternet.net/test.cgi
CLIENT_SIDE := $(FB)/dialog/oauth?client_id=$(APP_ID)&redirect_uri=$(REDIRECT)
CLIENT_SIDE := $(CLIENT_SIDE)&scope=$(PERMISSIONS)&response_type=code
SERVER_SIDE := $(GRAPH)/oauth/access_token?client_id=$(APP_ID)
SERVER_SIDE := $(SERVER_SIDE)&redirect_uri=$(REDIRECT)
SERVER_SIDE := $(SERVER_SIDE)&client_secret=$(APP_SECRET)&code=$(CODE)
LONG_LIVED := $(GRAPH)/oauth/access_token?client_id=$(APP_ID)
LONG_LIVED := $(LONG_LIVED)&client_secret=$(APP_SECRET)
LONG_LIVED := $(LONG_LIVED)&grant_type=fb_exchange_token
LONG_LIVED := $(LONG_LIVED)&fb_exchange_token=$(TOKEN)
ACCOUNTS := $(GRAPH)/me/accounts?access_token=$(TWOMONTHTOKEN)
export
env:
    env
    @echo Usage: make code
    @echo '        ' make CODE=codefrompreviousstep token
    @echo '        ' make TOKEN=tokenfrompreviousstep longterm
    @echo '        ' make TWOMONTHTOKEN=tokenfrompreviousstep accounts
    @echo Then edit '$$HOME/.netrc' replacing password with page token
code:
    $(BROWSER) "$(CLIENT_SIDE)"
token:
    $(BROWSER) "$(SERVER_SIDE)"
longterm:
    $(BROWSER) "$(LONG_LIVED)"
accounts:
    $(BROWSER) $(ACCOUNTS)

it turns out in many cases the first step fails with w3m. in that case, install another browser such as firefox; ssh -X to your server if the script is remotely hosted; and use make BROWSER=firefox code instead. the following steps should work with w3m as shown.

note: if cutting-and-pasting this Makefile, make sure to replace the 4-space indentations with proper tabs.

jcomeau_ictx
  • 37,688
  • 6
  • 92
  • 107
0

Using Facebook API v3.1 - None of the answers above worked for me. Instead, I had to:

1) Create a "system user"

2) Grant him access to the properties I needed (in my case an App)

3) Generate a new token for that app and system user

The instructions I used can be found here

Guy
  • 12,250
  • 6
  • 53
  • 70
-1

podrias intentar algo como esto

Administrar Paginas
<a href="#" class="btn" onclick="token_live()" >url</a>

                            <script type="text/javascript">
                                function token_live(){
                                    var token_app = "";
                                    $.ajax({
                                        url: "https://graph.facebook.com/v2.8/oauth/access_token?grant_type=fb_exchange_token&client_id=598062314053459&client_secret='client_secret'&fb_exchange_token=access_token",
                                        type: 'POST',
                                        dataType: 'HTML',
                                        data: {api_public: 'AP-42b3a8aab70',
                                        },
                                    })
                                    .done(function(data) {

            var txt = data
var obj = JSON.parse(txt);

    var token_live = obj.access_token

var url_infinit = "https://graph.facebook.com/v2.8/oauth/access_token?grant_type=fb_exchange_token&client_id='remplaza_cliente_id'&client_secret='client_secret'&fb_exchange_token="+token_live;

alert(url_infinit);

```