403 Forbidden while accessing Leycloak rest API with a valid user credentials - keycloak

I have set up a Keycloak server and a user named 'sample' is given permissions to access the rest ADMIN APIs, I granted permissions to the relevant realm and client_id. And I'm able to access the rest APIs using the postman service using this user credentials 'sample/sample'.
so through Angular application, I was trying to access the API that fetches the roles in a specific realm. since not all the login user will have the rest admin access, I'm using the user credentials(sample/sample) that have the access to admin API, but when I try to access the API, the APIs are forbidden,
this.getKeycloakAccessToken().subscribe((Tokres:any)=>{
console.log('accessToken: ', Tokres.body.access_token);
if(Tokres && Tokres.status === 200 && Tokres.body.access_token){
this.getKeycloakRoles(Tokres.body.access_token).subscribe((roleRes:any)=>{
console.log(roleRes);
},(roleErr:any)=>{
console.log('error while fetching roles..');
console.log(roleErr);
})
}
},(tokErr:any)=>{
console.log('error while accessing keycloak token...');
console.log(tokErr);
})
getKeycloakAccessToken(){
const url = 'http://keycloak-keycloak.router.default.svc.cluster.local.......nip.io/auth/realms/myRealm/protocol/openid-connect/token';
const authH = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
const body = new HttpParams()
.set('username', 'sample')
.set('password', 'sample')
.set('grant_type', 'password').set('client_id','rest-client');
return this.http.post(url, body,{headers:authH,observe:'response'});
}
getKeycloakRoles(access_token){
const url = 'http://keycloak-keycloak.router.default.svc.cluster.local........nip.io/auth/admin/realms/myRealm/roles'
const authH = new HttpHeaders().set('Authorization','Bearer ' + access_token);// ({'Authorization':'Bearer ' + access_token});
return this.http.get(url,{headers:authH,observe:'response'});
}
and when I tried to debug, the access_token shown in console is different from that of request headers
[![network log][2]][2]
After debugging for couple of days, I figured out the reason for the difference in Access token, the API call is being invoked with the access_token of logged in session, though the program has source code written to set the headers set with access token of user 'sample/sample'. is there any way to trigger the API with the given access_token rather with the logged in user's access_token.

This might not be the solution, but just a couple of workarounds that worked for me.
Allow permissions (set 'Relam Management') to all the logged in users from the key cloak admin console, this way irrespective of user, whoever logs in will be able access the rest Admin APIs, follow this below
reference
From keycloak client library, we have a initializeKeycloak() , that has configurations set for the application, so disable the 'enableBearerInterceptor' which will say the application not to use the access_token generated by logged in user to set the headers of each request. this way we can avoid the forbidden error.
But with approach no.2, you can not use the AT of logged in user as we r disabling the enableBearerInterceptor.
And with solution no.1, if you are not having control on who are the users logging in to your application, i,e using some third party tool like LDAP to set the users, then it this won't serve the solution.

Related

Maintain flask_login session in flutter

Soo...I have an app with flask backend and flutter frontend. It utilizes flask_login to manage users. Problem is - I don't know how to maintain session on client side. Flutter client gets response from server, but I don't see any token, or user_id inside.
So far, I've tried to parse responce, with no luck and I've used solution from How do I make an http request using cookies on flutter?
also, without success.
Server-side https://github.com/GreenBlackSky/COIN/blob/master/api_app/app/login_bp.py
Client-side https://github.com/GreenBlackSky/coin_web_client/blob/master/lib/session.dart
Maybe, using flask_login was not such a good idea after all..
Have you tried with the request_loader approach? You can log in from Flutter client using a url argument and the Authorization header. Quoting from the documentation,
For example, to support login from both a url argument and from Basic Auth using the Authorization header:
#login_manager.request_loader
def load_user_from_request(request):
# first, try to login using the api_key url arg
api_key = request.args.get('api_key')
if api_key:
user = User.query.filter_by(api_key=api_key).first()
if user:
return user
# next, try to login using Basic Auth
api_key = request.headers.get('Authorization')
if api_key:
api_key = api_key.replace('Basic ', '', 1)
try:
api_key = base64.b64decode(api_key)
except TypeError:
pass
user = User.query.filter_by(api_key=api_key).first()
if user:
return user
# finally, return None if both methods did not login the user
return None
If you don't want to use flask_login anymore, I would suggest flask_jwt_extended for your case. Note that authentication will be carried out using JWT tokens instead of sessions.
Basically, you would need to create three routes: one for creating access and refresh tokens when the user logged in, one for refreshing the expired access token with the refresh token and one for removing the tokens when the user logged out. Then you would protect your API endpoints with the #jwt_required decorators.
Please refer to the documentation for detailed implementation.

SharePoint keeps on asking credentials in pop up

We have created one SharePoint List custom form having Rest API and when users having Contribute access are trying to submit the form, they are getting pop up asking for credentials again and again. Although the functionality is working fine with Full Access and site collection admin users.
page is also becoming unresponsive after some time. Please assist
If you have client-side JavaScript executing REST calls, it will always run in the context of the current user, which means you cannot do anything in a REST call that the current user does not have permission to do themselves.
If you are using an on-premises installation of SharePoint Server that is using integrated NTLM security (meaning your Active Directory users are usually automatically logged into SharePoint without entering their credentials), then when your code attempts a client-side REST call that attempts to perform an action that the current user is not authorized for, the browser will automatically prompt them for AD credentials for a user account that Does have access.
If you are using an Online environment or one without integrated security, then instead of re-prompting the users for credentials, your code will just receive a 401 Unauthorized.
If your SharePoint farm is using integrated security with your local domain, there is no way to directly stop the user from being prompted for credentials when you try to access a resource they do not have access to. Instead, you will need to use the REST API to see if the current user has permission to perform the action, and display a more friendly error if they do not.
The following is an example, borrowed from a previous stack exchange post on checking a user's permissions:
function checkPermissions() {
var call = jQuery.ajax({
url: _spPageContextInfo.webAbsoluteUrl +
"/_api/Web/effectiveBasePermissions",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data, textStatus, jqXHR) {
var manageListsPerms = new SP.BasePermissions();
manageListsPerms.initPropertiesFromJson(data.d.EffectiveBasePermissions);
var manageLists = manageListsPerms.has(SP.PermissionKind.manageLists);
var message = jQuery("#message");
message.text("Manage Lists: " + manageLists);
});
}

MSAL, Azure MobileService and Auto REST calls get 401 Unauthorized

I have an app (currently in UWP) that makes use of MobileServiceClient and AutoRest to an Azure App Service API App. I successfully used the winfbsdk and can authenticate thru that and then get it to login to MobileService.LoginAsync with the FB access token as a JObject. I also take that JObject and send it in the x-zumo-auth header when making calls to the API App via AutoRest within the app.
What I would like to do is be able to authenticate using MicrosoftAccount. If I use MobileService.LoginAsync, I cannot get the proper token and pass it along to AutoRest - it always comes back as 401 Unauthorized.
I tried to used MSAL, but it returns a Bearer token and passing that along also comes back as 401 Unauthorized.
Is there any good way to do this? I started on the route of MSAL since that would support Windows desktop, UWP and Xamarin Forms which will be ideal. I just need info on how to get the proper token from it to pass along to an AutoRest HttpClient that goes back to the Azure App Service API App.
Update:
If I use the following flow, it works with Facebook, but not with MicrosoftAccount.
-Azure AppService with WebAPI (and swagger for testing via a browser)-Security setup through the Azure Dashboard on the service and configured to allow Facebook or MicrosoftAccount
1. On my UWP app, using winfbsdk, I login with Facebook, then grab the FBSession.AccessTokenData.AccessToken and insert that into a JObject:
JObject token = JObject.FromObject
(new{access_token = fbSession.AccessTokenData.AccessToken});
2. Login to MobileServiceClient
user = await App.MobileService.LoginAsync
(MobileServiceAuthenticationProvider.Facebook, token);
Login to API App with HttpClient and retrieve the token to use in X-ZUMO-AUTH
using (var client = new HttpClient())
{
client.BaseAddress = App.MobileService.MobileAppUri;
var jsonToPost = token;
var contentToPost = new StringContent(
JsonConvert.SerializeObject(jsonToPost),
Encoding.UTF8, "application/json");
var asyncResult = await client.PostAsync(
"/.auth/login/" + provider.ToString(),
contentToPost);
if (asyncResult.Content == null)
{
throw new InvalidOperationException("Result from call was null.");
return false;
}
else
{
if (asyncResult.StatusCode == System.Net.HttpStatusCode.OK)
{
var resultContentAsString = asyncResult.Content.AsString();
var converter = new ExpandoObjectConverter();
dynamic responseContentAsObject = JsonConvert.DeserializeObject<ExpandoObject>(
resultContentAsString, converter);
var applicationToken = responseContentAsObject.authenticationToken;
ApiAppClient.UpdateXZUMOAUTHToken(applicationToken);
}
}
}
ApiAppClient.UpdateXZUMOAUTH call just does the following:
if (this.HttpClient.DefaultRequestHeaders.Contains("x-zumo-auth") == true)
{
this.HttpClient.DefaultRequestHeaders.Remove("x-zumo-auth");
}
this.HttpClient.DefaultRequestHeaders.Add("x-zumo-auth", applicationToken);
Any subsequent calls using the ApiAppClient (created with AutoRest from the swagger json of my Azure AppService WebAPI) contain the x-zumo-auth header and are properly authenticated.
The problem occurs when trying to use MicrosoftAccount. I cannot seem to obtain the proper token to use in x-zumo-auth from either MSAL or LoginWithMicrosoftAsync.
For #1 above, when trying for MicrosoftAccount, I used MSAL as follows:
AuthenticationResult result = await MSAuthentication_AcquireToken();
JObject token = JObject.FromObject(new{access_token = result.Token});
And MSAuthentication_AcquireToken is defined below, using interfaces and classes as suggested in the Azure samples: https://github.com/Azure-Samples/active-directory-xamarin-native-v2
private async Task<AuthenticationResult> MSAuthentication_AcquireToken()
{
IMSAcquireToken at = new MSAcquireToken();
try
{
AuthenticationResult res;
res = await at.AcquireTokenAsync(App.MsalPublicClient, App.Scopes);
return res;
}
}
Update - ok with MobileServiceClient, but still not working with MSAL
I got it working with MobileServiceClient as follows:
1. Use MobileService.LoginAsync
2. Take the returned User.MobileServiceAuthenticationToken
3. Set the X-ZUMO-AUTH header to contain the User.MobileServiceAuthenticationToken
user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
applicationToken = user.MobileServiceAuthenticationToken;
ApiAppClient.UpdateAppAuthenticationToken(applicationToken);
MSAL still not working!
So the original question still remains, what part of the token returned from MSAL do we need to pass on to X-ZUMO-AUTH or some other header so that calls to the Azure AppService WebAPI app will authenticate?
I have an app (currently in UWP) that makes use of MobileServiceClient and AutoRest to an Azure App Service API App. I successfully used the winfbsdk and can authenticate thru that and then get it to login to MobileService.LoginAsync with the FB access token as a JObject. I also take that JObject and send it in the x-zumo-auth header when making calls to the API App via AutoRest within the app.
According to your description, I assumed that you are using Client-managed authentication. You directly contact the identity provider and then provide the token during the login with your mobile back-end, then you could leverage MobileServiceClient.InvokeApiAsync to call your API APP, which would add the X-ZUMO-AUTH header with the value authenticationToken after you invoke MobileServiceClient.LoginAsync(MobileServiceAuthenticationProvider.Facebook, token);
What I would like to do is be able to authenticate using MicrosoftAccount. If I use MobileService.LoginAsync, I cannot get the proper token and pass it along to AutoRest - it always comes back as 401 Unauthorized. I tried to used MSAL, but it returns a Bearer token and passing that along also comes back as 401 Unauthorized. Is there any good way to do this?
AFAIK, for the client-flow authentication patterns (AAD, Facebook, Google), the token parameter for LoginAsync would look like {"access_token":"{the_access_token}"}.
For the client-flow authentication (Microsoft Account), you could leverage MobileServiceClient.LoginWithMicrosoftAccountAsync("{Live-SDK-session-authentication-token}"), also you could use LoginAsync with the token parameter of the value {"access_token":"{the_access_token}"} or {"authenticationToken":"{Live-SDK-session-authentication-token}"}. I have tested LoginAsync with the access_token from MSA and retrieve the logged info as follows:
In summary, when you retrieve the authentionToken after you have logged with your mobile back-end, you could add the X-ZUMO-AUTH header to each of your API APP requests with the authentionToken.
For more details, you could refer to this official document about authentication works in App Service.
UPDATE
I have checked this https://github.com/Azure-Samples/active-directory-xamarin-native-v2 and used fiddler to capture the network packages when authenticating the user and get an access token. I found that MSAL is working against Microsoft Graph and REST and when the user is logged, you could only retrieve the access_token and id_token, and both of them could not be used for single sign-on with your mobile back-end.
While the official code sample about Client-managed authentication for Azure Mobile Apps with MSA is using the Live SDK. As the Live SDK REST API mentioned about signing users, you could get an access token and an authentication token which is used for single sign-on scenario. Also, I have checked the Server-managed authentication and found that app service authentication / authorization for MSA also uses the Live SDK REST API.
In summary, you could not use MSAL for client-managed authentication with MSA, for client-managed authentication, you need to leverage Live SDK to retrieve the authentication_token then invoke MobileServiceClient.LoginWithMicrosoftAccountAsync("{Live-SDK-session-authentication-token}") to retrieve the authenticationToken from your mobile backend. Or you could just leverage server-managed authentication for MSA. For more details about Live SDK, you could refer to LiveSDK.

Facebook access user info if they are not logged in

Ok, so what I am trying to do is a bit odd, so I can't find anything that gives me even a remote idea about how to do this.
I need to access my personal profile posts:
FB.api("/" + myPersonalUserId + "/feed", {limit: 5}, function(data){
console.log(data);
// do stuff with my user info
});
in order to display them on my personal webite, similar to a dynamic blog. But I want it to automatically retrieve these posts without my having to be signed in on each computer that wants to view my site.
Before you get sidetracked on the init, I am using an app and app id that my personal user account has verified access to all permissions.
I know it will require the use of an access token, but how do I get a valid access token without being logged into that computer?
Honestly, I'm starting to question if it is even possible, but if anyone knows how I could accomplish this, that would be awesome!
The best way to achieve this is to just cache the data in your own database and refresh it whenver the user uses your App again.
If that´s not good enough, you have to generate and store an Extended User Token. How to create one is explained in the docs:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
Extended User Tokens are valid for 60 days, there is no User Token that is valid forever. And you should never use Tokens directly on the client, because some user could just copy it from the source. Tokens are meant to be secret, so use it on the server only. You don´t need to use the PHP SDK, a simple CURL call to the Graph API will do it:
https://graph.facebook.com/[your-app-scoped-id]/feed?access_token=[extended-user-token]
Ok, so I found a solution similar to the one above, but offers a permanent access token.
first, build a url:
url = 'https://graph.facebook.com/v2.5/' + {app user Id, not public Id} + '/feed';
url += '?access_token=' + {app Id} + '|' + {app secret};
url += '&fields=id,name,message,full_picture,created_time'; // these scopes should be approved by corresponding user
url += '&limit=5';
then run it by calling a simple ajax request. These variables should be served from the server through ajax, not hardcoded on the client

Facebook: Permanent Page Access Token?

I work on a project that has Facebook pages as one of its data sources. It imports some data from it periodically with no GUI involved. Then we use a web app to show the data we already have.
Not all the information is public. This means I have to get access to the data once and then keep it. However, I don't know the process and I haven't found a good tutorial on that yet. I guess I need an access_token, how can I get it from the user, step by step? The user is an admin of a facebook page, will he have to add some FB app of ours to the page?
EDIT: Thanks #phwd for the tip. I made a tutorial how to get a permanent page access token, even with offline_access no longer existing.
EDIT: I just found out it's answered here: Long-lasting FB access-token for server to pull FB page info
Following the instructions laid out in Facebook's extending page tokens documentation I was able to get a page access token that does not expire.
I suggest using the Graph API Explorer for all of these steps except where otherwise stated.
0. Create Facebook App
If you already have an app, skip to step 1.
Go to My Apps.
Click "+ Add a New App".
Setup a website app.
You don't need to change its permissions or anything. You just need an app that wont go away before you're done with your access token.
1. Get User Short-Lived Access Token
Go to the Graph API Explorer.
Select the application you want to get the access token for (in the "Application" drop-down menu, not the "My Apps" menu).
Click "Get Token" > "Get User Access Token".
In the pop-up, under the "Extended Permissions" tab, check "manage_pages".
Click "Get Access Token".
Grant access from a Facebook account that has access to manage the target page. Note that if this user loses access the final, never-expiring access token will likely stop working.
The token that appears in the "Access Token" field is your short-lived access token.
2. Generate Long-Lived Access Token
Following these instructions from the Facebook docs, make a GET request to
https://graph.facebook.com/v2.10/oauth/access_token?grant_type=fb_exchange_token&client_id={app_id}&client_secret={app_secret}&fb_exchange_token={short_lived_token}
entering in your app's ID and secret and the short-lived token generated in the previous step.
You cannot use the Graph API Explorer. For some reason it gets stuck on this request. I think it's because the response isn't JSON, but a query string. Since it's a GET request, you can just go to the URL in your browser.
The response should look like this:
{"access_token":"ABC123","token_type":"bearer","expires_in":5183791}
"ABC123" will be your long-lived access token. You can put it into the Access Token Debugger to verify. Under "Expires" it should have something like "2 months".
3. Get User ID
Using the long-lived access token, make a GET request to
https://graph.facebook.com/v2.10/me?access_token={long_lived_access_token}
The id field is your account ID. You'll need it for the next step.
4. Get Permanent Page Access Token
Make a GET request to
https://graph.facebook.com/v2.10/{account_id}/accounts?access_token={long_lived_access_token}
The JSON response should have a data field under which is an array of items the user has access to. Find the item for the page you want the permanent access token from. The access_token field should have your permanent access token. Copy it and test it in the Access Token Debugger. Under "Expires" it should say "Never".
Here's my solution using only Graph API Explorer & Access Token Debugger:
Graph API Explorer:
Select your App from the top right dropdown menu
Select "Get User Access Token" from dropdown (right of access token field) and select needed permissions
Copy user access token
Access Token Debugger:
Paste copied token and press "Debug"
Press "Extend Access Token" and copy the generated long-lived user access token
Graph API Explorer:
Paste copied token into the "Access Token" field
Make a GET request with "PAGE_ID?fields=access_token"
Find the permanent page access token in the response (node "access_token")
(Optional) Access Token Debugger:
Paste the permanent token and press "Debug"
"Expires" should be "Never"
(Tested with API Version 2.9-2.11, 3.0-3.1)
In addition to the recommended steps in the Vlasec answer, you can use:
Graph API explorer to make the queries, e.g. /{pageId}?fields=access_token&access_token=THE_ACCESS_TOKEN_PROVIDED_BY_GRAPH_EXPLORER
Access Token Debugger to get information about the access token.
Another PHP answer to make lives easier. Updated for Facebook Graph API 2.9 . Just fill 'er up and load.
<?php
$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
'usertoken'=>'',
'appid'=>'',
'appsecret'=>'',
'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
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/v2.9/me?access_token={$longtoken}")); // get user id
$userid=$r->id;
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/{$userid}?fields=access_token&access_token={$longtoken}")); // get permanent token
if($r->id==$args['pageid']) $finaltoken=$r->access_token;
return $finaltoken;
}
?>
Addendum: (alternative)
Graph 2.9 onwards , you can skip much of the hassle of getting a long access token by simply clicking Extend Access Token at the bottom of the Access Token Debugger tool, after having debugged a short access token. Armed with information about pageid and longlivedtoken, run the php below to get permanent access token.
<?php
$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
'longlivedtoken'=>'',
'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
function generate_token($args){
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/{$args['pageid']}?fields=access_token&access_token={$args['longlivedtoken']}"));
return $r->access_token;
}
?>
Although the second code saves you a lot of hassle, I recommend running the first php code unless you are in a lot of hurry because it cross-checks pageid and userid. The second code will not end up working if you choose user token by mistake.
Thanks to dw1 and Rob
I made a PHP script to make it easier. Create an app. In the Graph API Explorer select your App and get a user token with manage_pages and publish_pages permission. Find your page's ID at the bottom of its About page. Fill in the config vars and run the script.
<?php
$args=[
'usertoken'=>'',
'appid'=>'',
'appsecret'=>'',
'pageid'=>''
];
echo generate_token($args);
function generate_token($args){
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/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/v2.8/me?access_token={$longtoken}")); // get user id
$userid=$r->id;
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/{$userid}/accounts?access_token={$longtoken}")); // get permanent token
foreach($r->data as $d) if($d->id==$args['pageid']) return $d->access_token;
}
I tried these steps:
https://developers.facebook.com/docs/marketing-api/access#graph-api-explorer
Get Permanent Page Access Token
Go to Graph API Explorer
Select your app in Application
Paste the long-lived access token into Access Token
Next to Access Token, choose the page you want an access token for. The access token appears as a new string.
Click i to see the properties of this access token
Click “Open in Access Token Tool” button again to open the “Access Token Debugger” tool to check the properties
One Tip, it only worked for me when the page language is english.
As all the earlier answers are old, and due to ever changing policies from facebook other mentioned answers might not work for permanent tokens.
After lot of debugging ,I am able to get the never expires token using following steps:
Graph API Explorer:
Open graph api explorer and select the page for which you want to obtain the access token in the right-hand drop-down box, click on the Send button and copy the resulting access_token, which will be a short-lived token
Copy that token and paste it in access token debugger and press debug button, in the bottom of the page click on extend token link, which will extend your token expiry to two months.
Copy that extended token and paste it in the below url with your pageId, and hit in the browser url
https://graph.facebook.com/{page_id}?fields=access_token&access_token={long_lived_token}
U can check that token in access token debugger tool and verify Expires field , which will show never.
Thats it
Most of the answers above now doesn't give permanent token, they only extend it to 2 months. Here's how I got it:
From Graph Explorer tool, select the relevant permissions and get the short lived page access token.
Go to debugger tool and paste your access token. Then, click on 'Extend Token' button at the bottom of the page.
Copy the the extended token and use it in this API:
https://graph.facebook.com/v2.10/me?fields=access_token&access_token=<extended_access_token>
This should return you the permanent access token. You can verify it in debugger tool, the expires at field should say 'Never'.
If you are requesting only page data, then you can use a page access token. You will only have to authorize the user once to get the user access token; extend it to two months validity then request the token for the page. This is all explained in Scenario 5. Note, that the acquired page access token is only valid for as long as the user access token is valid.
While getting the permanent access token I followed above 5 steps as Donut mentioned. However in the 5th step while generating permanent access token its returning the long lived access token(Which is valid for 2 months) not permanent access token(which never expires). what I noticed is the current version of Graph API is V2.5. If you trying to get the permanent access token with V2.5 its giving long lived access token.Try to make API call with V2.2(if you are not able to change version in the graph api explorer,hit the API call https://graph.facebook.com/v2.2/{account_id}/accounts?access_token={long_lived_access_token} in the new tab with V2.2) then you will get the permanent access token(Which never expires)
In addition to mentioned methods it is worth mentioning that for server-to-server applications, you can also use this form of permanent access token:
app_id|app_secret
This type of access token is called App Token. It can generally be used to call Graph API and query for public nodes within your application back-end.
It is mentioned here: https://developers.facebook.com/docs/facebook-login/access-tokens
If you have facebook's app, then you can try with app-id & app-secret.
Like :
access_token={your-app_id}|{your-app_secret}
it will don't require to change the token frequently.
Thanks to #donut I managed to get the never expiring access token in JavaScript.
// Initialize exchange
fetch('https://graph.facebook.com/v3.2/oauth/access_token?grant_type=fb_exchange_token&client_id={client_id}&client_secret={client_secret}&fb_exchange_token={short_lived_token}')
.then((data) => {
return data.json();
})
.then((json) => {
// Get the user data
fetch(`https://graph.facebook.com/v3.2/me?access_token=${json.access_token}`)
.then((data) => {
return data.json();
})
.then((userData) => {
// Get the page token
fetch(`https://graph.facebook.com/v3.2/${userData.id}/accounts?access_token=${json.access_token}`)
.then((data) => {
return data.json();
})
.then((pageToken) => {
// Save the access token somewhere
// You'll need it at later point
})
.catch((err) => console.error(err))
})
.catch((err) => console.error(err))
})
.catch((err) => {
console.error(err);
})
and then I used the saved access token like this
fetch('https://graph.facebook.com/v3.2/{page_id}?fields=fan_count&access_token={token_from_the_data_array}')
.then((data) => {
return data.json();
})
.then((json) => {
// Do stuff
})
.catch((err) => console.error(err))
I hope that someone can trim this code because it's kinda messy but it was the only way I could think of.
Application request limit reached (#4) - FB API v2.1 and greater
This answer led me to the "ultimate answer for us" and so it is very much related so I am appending it here. While it's related to the above it is different and it seems FB has simplified the process some.
Our sharing counts on our site stopped worked when FB rolled over the api to v 2.1. In our case we already had a FB APP and we were NOT using the FB login. So what we needed to do was get a FB APP Token to make the new requests. This is as of Aug. 23 2016.
Go to: https://developers.facebook.com/tools/explorer
Select the api version and then use GET and paste the following:
/oauth/access_token?client_id={app-id}&client_secret={app-secret}&grant_type=client_credentials
You will want to go grab your app id and your app secret from your app page. Main FB Apps developer page
Run the graph query and you will see:
{
"access_token": "app-id|app-token",
"token_type": "bearer"
}
Where "app-id" and "app-token" will be your app id from your FB app page and the generated FB App HASH you just received.
Next go test your new APP access token: FB Access Token tester
You should see, by pasting the "app-token" into the token tester, a single app based token without an expiration date/time.
In our case we are using the FB js sdk so we changed our call to be like so (please note this ONLY gets the share count and not the share and comment count combined like it used to be):
FB.api(
'/','GET',{
// this is our FB app token for our FB app
access_token: FBAppToken,
"id":"{$shareUrl}","fields":"id,og_object{ engagement }"
}
This is now working properly. This took a lot of searching and an official bug report with FB to confirm that we have to start making tokenized requests to the FB api. As an aside I did request that they (FB) add a clue to the Error code (#4) that mentions the tokenized request.
I just got another report from one of our devs that our FB comment count is broken as well due to the new need for tokenized requests so I will update this accordingly.
Many of these examples do not work, not sure if it's because of 2.9v coming out but I was banging my head. Anyways I took #dw1 version and modified it a little with the help of #KFunk video and got this working for me for 2.9. Hope this helps.
$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
'usertoken'=>'',
'appid'=>'',
'appsecret'=>'',
'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
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;
}
As of April 2020, my previously-permanent page tokens started expiring sometime between 1 and 12 hours. I started using user tokens with the manage_pages permission to achieve the previous goal (polling a Page's Events). Those tokens appear to be permanent.
I created a python script based on info found in this post, hosted at github.com/k-funk/facebook_permanent_token, to keep track of what params are required, and which methods of obtaining a permanent token are working.
I created a small NodeJS script based on donut's answer. Store the following in a file called get-facebook-access-token.js:
const fetch = require('node-fetch');
const open = require('open');
const api_version = 'v9.0';
const app_id = '';
const app_secret = '';
const short_lived_token = '';
const page_name = '';
const getPermanentAccessToken = async () => {
try {
const long_lived_access_token = await getLongLivedAccessToken();
const account_id = await getAccountId(long_lived_access_token);
const permanent_page_access_token = await getPermanentPageAccessToken(
long_lived_access_token,
account_id
);
checkExpiration(permanent_page_access_token);
} catch (reason) {
console.error(reason);
}
};
const getLongLivedAccessToken = async () => {
const response = await fetch(
`https://graph.facebook.com/${api_version}/oauth/access_token?grant_type=fb_exchange_token&client_id=${app_id}&client_secret=${app_secret}&fb_exchange_token=${short_lived_token}`
);
const body = await response.json();
return body.access_token;
};
const getAccountId = async (long_lived_access_token) => {
const response = await fetch(
`https://graph.facebook.com/${api_version}/me?access_token=${long_lived_access_token}`
);
const body = await response.json();
return body.id;
};
const getPermanentPageAccessToken = async (
long_lived_access_token,
account_id
) => {
const response = await fetch(
`https://graph.facebook.com/${api_version}/${account_id}/accounts?access_token=${long_lived_access_token}`
);
const body = await response.json();
const page_item = body.data.find(item => item.name === page_name);
return page_item.access_token;
};
const checkExpiration = (access_token) => {
open(`https://developers.facebook.com/tools/debug/accesstoken/?access_token=${access_token}&version=${api_version}`);
}
getPermanentAccessToken();
Fill in the constants and then run:
npm install node-fetch
npm install open
node get-facebook-access-token.js
After running the script a page is opened in the browser that shows the token and how long it is valid.
I found this answer which refers to this tool which really helped a lot.
I hope this answer is still valid when you read this.