On facebook documentation page, there is written:
Facebook::getAccessToken()
Get the current access token being used by the SDK. This may be a user access token or an application access token. See the permissions page for more information on access tokens.
But there is no explanation how to force the method to return app token, not the user token. It is not exmplained nor on permission page.
Cn anybody help, how this method works?
The App access_token is usually just APP_ID|APP_SECRET. In my code, I tend to just do this:
$app_token = APP_ID . '|' . APP_SECRET;
Related
I want to get the each user's FB posts by commandline.
like
whitebear#bear.com
blackbear#bear.com
yellowbear#bear.com
These are my code.
$secret = 'xxxxx';
$key = 'xxxx';
$url = "https://graph.facebook.com/oauth/access_token?client_id="
. $key . "&client_secret=" . $secret . "&grant_type=client_credentials";
print $url. "\n";
$json = json_decode(file_get_contents($url),true);
var_dump($json['access_token']); // success
$url2 = "https://graph.facebook.com/me?fields=posts&access_token=" .$json['access_token'];
$json2 = json_decode(file_get_contents($url2),true);
var_dump($json2); //
Warning: file_get_contents(https://graph.facebook.com/me?fields=posts&access_token=4887415xxxxxxxxxxxxxxx): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
I succeed to get the access_token, however I think it is facebook app's accesstoken?? not user's??
I think I should indicate the who is the user before loading me? api.
However how should I do?
I let every user login on web application AOuth and stored each users facebook_access_token in DataBase (but it valid a few hours????)
If you need to store a User Token, you should use an Extended User Token
You cannot get a User Token programmatically, only on user interaction with a proper login process
You can debug Tokens to see if it is an App or User Token in the Token Debugger
More Information: https://developers.facebook.com/docs/facebook-login/access-tokens/
grant_type=client_credentials generates an app token.
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.
Some user data that would normally be visible to an app 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.
You can not use app tokens to access me or fetch most data about individual users.
I am using php oauth2 library from this github repo.
PHP oauth2 library
Whenever i send a refresh token, I receive new access token with old scopes.
But i want to change the scopes returned with new access token.
When i first generate a token using user credentials grant type, I get the supported scopes for the user and store them this way.
$defaultScope = implode(" ", $scopes);$memory = new OAuth2\Storage\Memory(array('default_scope' =>$defaultScope));
$scopeUtil = new OAuth2\Scope($memory);
$this->server->setScopeUtil($scopeUtil);
$this->server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
where $scopes is an array
for example $scopes=array("ADDUSER","EDITUSER","EDITROLE");
similarly , if i send refresh token using refresh_token grant type and run this with modified $scopes
for example $scopes=array("ADDUSER", "EDITROLE");
$defaultScope = implode(" ", $scopes);$memory = new OAuth2\Storage\Memory(array('default_scope' =>$defaultScope));
$scopeUtil = new OAuth2\Scope($memory);
$this->server->setScopeUtil($scopeUtil);
$this->server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
I receive same old scopes("ADDUSER EDITUSER EDITROLE") which were set when new access token generated using user credentials grant type.
SO is there a way to change scopes when new access token is generated using refresh token ?
or am i doing something wrong here?
A Client can "down-scope" when it asks for a new access token in the refresh token grant, see the documentation around scope in the spec here: https://www.rfc-editor.org/rfc/rfc6749#section-6 Yet your Authorization server may or may not support that.
I am using the Lusitanian PHP Oauth library (https://github.com/Lusitanian/PHPoAuthLib).
After the user gets authorized in my application, i have received values of Access Token and Access Token Secret. Now with these values, i would like to make authenticated calls to API. How can i make the calls with the values of Access Token, Access Token Secret, along with the values of Consumer Key and Consumer Secret? I don't want to get the user authorized every time, to make API calls for him. Does anyone have an idea ?
My request goes like this:
$result = json_decode( $service->request( '/users/getDetails' ), true
);
I have tried the REST Client of Firefox and Advanced REST Client of Chrome, that perform OAuth calls successfully, with just the values of Access Token, Access Token Secret, Consumer Key and Consumer Secret.
Similarly, i would like to perform the OAuth calls from my PHP code. The library which i am using, depends on Session to store these values (which requires the user to login each time) and build the Authorization header and signature. Is there a way i can build the Signature and Authorization header from my end manually and make the OAuth calls ?
Finally, i have tweaked the functionality of reusing the access tokens.
I am fetching token from a config php file, after i store the token in it.
The token can also be stored in a local PHP session and read from it.
The code for storing token is in Service/AbstractService.php:
$this->storage->storeAccessToken($this->service(), $token);
You can modify it like the following, to store the token in a session variable:
if(!isset($_SESSION['access_token'])) {
$token = new StdOAuth1Token();
$token->setRequestToken($access_token);
$token->setRequestTokenSecret($access_token_secret);
$token->setAccessToken($access_token);
$token->setAccessTokenSecret($access_token_secret);
$token->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES);
$_SESSION['access_token'] = serialize($token);
}
Then when making a request to API, you can modify the code in request() function to use token from your session:
Change:
$token = $this->storage->retrieveAccessToken($this->service());
To:
$token = unserialize($_SESSION['access_token']);
This way, i could use custom PHP sessions to store and retrieve access tokens. You can also use Database or a text file to store and retrieve the tokens. It works! Hope it would be useful for someone.
I am using the following URL to get a Facebook Auth Token for managing Pages and Page Events...
https://www.facebook.com/dialog/oauth?client_id=CLIENTID&redirect_uri=REDIRECTURL&scope=manage_pages,create_event&response_type=token
This goes through the authorization process and returns the token, which gets saved in my database. I then try to do the following to retrieve the thumbnail images of people attending one of the Page's Events...
function fbEventRSVPPhotos($eventID){
$authToken = eto_get_option('eto_auth_fbauthtoken') //pulled from database;
$json = file_get_contents("https://graph.facebook.com/" . $eventID ."/attending?access_token=" . $authToken);
$attendees = json_decode($json, true);
echo '<div class=attendee-photos>';
foreach($attendees['data'] as $attendee) {
echo '<img class="facebook-thumb toggleTooltip" title="' . $attendee['name'] . ' is attending" src="https://graph.facebook.com/' . $attendee['id'] . '/picture?type=square">';
}
echo '</div>';
}
This function works great for when I am logged in to Facebook, however once I log out I get the following...
Warning: file_get_contents(https://graph.facebook.com/MYEVENTID/attending?access_token=MYTOKEN) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in PATHTOSCRIPT on line 94
Warning: Invalid argument supplied for foreach() in PATHTOSCRIPT on line 97
And then it continues to show this PHP error even after logging back in. I essentially have to regenerate the auth token every time I log back in.
Can someone help me understand why this is happening and how to fix?
You want to destroy the session $facebook->destroySession(), not invalidate the token. Logging out is one of the ways to invalidate the token. This is the expected action.
Destroying the session will log the user out of the app but not invalidate the token. Seeing that you are saving it to a database, you are probably requesting access longer than two hours which is past the limitation of a short lived token.
Also as you are using a page you can use scenario 5 at https://developers.facebook.com/roadmap/offline-access-removal/
When a user grants an app the manage_pages permission, the app is able
to obtain page access tokens for pages that the user administers by
querying the [User ID]/accounts Graph API endpoint. With the migration
enabled, when using a short-lived user access token to query this
endpoint, the page access tokens obtained are short-lived as well.
Exchange the short-lived user access token for a long-lived access
token using the endpoint and steps explained earlier. By using a
long-lived user access token, querying the [User ID]/accounts endpoint
will now provide page access tokens that do not expire for pages that
a user manages. This will also apply when querying with a non-expiring
user access token obtained through the deprecated offline_access
permission.
I've this error, but not always. (I use PHP SDK, latest version).
If I'm logged into facebook and i try to register and login, then the app say it's ok!
Also if i'm not logged into facebook, the app redirect me to login url, and here it's all ok.
But sometimes the app say this exception: OAuthException: An active access token must be used to query information about the current user. and the script redirect the user to loginUrl with a loop-redirect (because the access token isn't valid and user need always of loginUrl)
In the web some say that Facebook create a duplicate of Access Token and then access token of php sdk don't is = facebook.
For fix, the user must deletes cookies, how I can fix this?
Thanks a lot for reply, if code is need reply and I'll post it, have a good day! :)
Try to destroy the Facebook session, then redirect the user to login URI if you receive this error, this way you will get a fresh access token.
Notice: Access token expire after a very short, you can get a long living access token. The latest PHP SDK contains a public function called : setExtendedAccessToken()
you can call this function to automatically exchange the 2-3 hours living access token for a 60 days access token
Eg:
try {
$user = $this->facebooknew->api('/me');
$this->facebooknew->setExtendedAccessToken();
$access_token = $this->facebooknew->getAccessToken();
}
catch(FacebookApiException $e){
$this->facebooknew->destroySession();
header('Location: ' . $this->facebooknew->getLoginUrl($params));
//echo $e;
}