Facebook access_token not valid - php

I am building a little website for an event. The idea is to add the attending persons from the facebook event to this website. The problem is that the attending service needs an access_token. I don't want a user to log in to the app, I just want to use the app access_token. But this doesn't seem to work.
I have the following php code for receiving the access_token:
// get facebook auth_token
$FB_APP_ID = '****';
$FB_APP_SECRET = '***';
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=" . $FB_APP_ID . "&client_secret=" . $FB_APP_SECRET . "&grant_type=client_credentials";
$app_token = file_get_contents($token_url);
parse_str($app_token); // creates: $access_token
In javascript I am using the following code:
/**
* Gets all the attending Users
* #param function callback: the function to call, when data loading is ready
* #param function callback: the function to call, when data loading is broken
* #return void
*/
this.getAttending = function(callback, errorHandler)
{
FB.api('/' + this.eventId + '/attending', function(response) {
if(response.error) {
errorHandler(response.error['message']);
} else {
callback(response.data);
}
} , {access_token: facebook.accessToken} );
}
I receive the error:
Invalid OAuth access token.
The access token looks like:
111737995591905|l9e3niEMM1RsIUhwHZv3pn3c19M
THe user access token looks like:
145634995501895|2.AQBcWfbvdzhloLYc.3600.1312138800.1-1146858041|cjCkHZqquyyFyX2dY0q2YCaSyy0
When i try to use the user access token, everything works fine. But when I hardcode the token, this will not work for other users. When I try the token that the server parsed for me, I get die invalid token action. Does somebody knows a solution for this?
It is a public event, and I don't want the user to login before he/she knows who is attending?
Is this possible at all?
Thanx!

Did you encode the token while hard coding? | should be %7C .
Cant think of anything else that might have gone wrong for the moment

Why not get an access token for yourself and then hard code that in your application (assuming it is running on a secure server where no one else can steal the credentials). Then anyone visiting the page can view the guest list using your own access token which is permissioned to view the list.
The client_credentials grant type is not meant for accessing user data, only application data. I don't know how the rest of the application works but I'm assuming that you need a user access token to see user data.

The way i got around this was designating the offline_access permission, it generates an access token that never expires so you can use it indefinitely. You would then in theory authorize only your Facebook account to have the event data pulled from it. You could then view and serve your event details to your website no problem.

Related

Storing the Google OAuth Authorization Token in Database

I am building a portal where multiple users can log in to their multiple Gmail accounts. I have successfully retrieved the token value, However, I want to store that in my database but I am unable to store it.
Below is the code I am using:
function mInititalize(){
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://mail.google.com/');
$client->setClientId(Config('gmail.client_id'));
$client->setClientSecret(Config('gmail.client_secret'));
$client->setRedirectUri('http://localhost:81'.Config('gmail.redirect_url'));
$loginURL = $client->createAuthUrl();
return redirect($loginURL);
}
After Redirection or user login
function mGetToken(){
$token = $client->fetchAccessTokenWithAuthCode( 'code'); // here i get the 'code' from login URL
I pass this code to get token I successfully get token
$oAuth = new Google_Service_Oauth2( $client);
$userData = $oAuth->userinfo_v2_me->get(); // get current user detail
}
I want to store $token value in database, but I am getting error message
>Serialization of 'Closure' is not allowed
Please anyone help me to solve this issue. Thanks.
I would suggest storing OAuth credential information for the Google API, not in your database, but through the API itself. If you're intending to use it any authentication manner, you'll run into problems, as the docs state:
Access tokens periodically expire and become invalid credentials for a related API request. Google Identity Platform: Using OAuth 2.0 for Web Server Applications
But, the same docs also show a way that you can set or retrieve the token natively within the API. Since it's data relating to google's auth'ing process, and since it might go stale if you store it, it seems best to just let them handle it and work with the API. The same source:
If you need to apply an access token to a new Google_Client object—for example, if you stored the access token in a user session—use the setAccessToken method:
$client->setAccessToken($access_token);
$client->getAccessToken();

Facebook Login and get post by command line

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.

How can I verify firebase token server side?

I have a firebase account where I manually create the users who will be abled to use my site (sign up is not public, but it is not relevant to this inquiry)
In the login page, the authentication is through javascript.
Once the user enters their mail and password the corresponding function is executed, I get the token and I send it to my PHP server via url redirection. Something like this:
firebase.auth().signInWithEmailAndPassword(inputemail, inputpassw)
.then( function(user) {
myEmail = user.email;
myUid = user.uid;
user.getIdToken()
.then( function(token){
myToken = token;
location.href = "http://www.example.com/verify?email="+myEmail+"&token="+myToken+"&uid="+myUid;
});
}, function (error) {
...
});
Then, on my server I will have the mail, the uid, and the token.
So, my question is:
How do I verify that the token is valid? It is impossible?
I know the token is encrypted, but the key is public... so anyone could make a valid token!
I mean, for instance, I have an expired token, I can decode it, change the expiration time, encode it again and gain access to my server without knowing any password
Is there something I'm missing?
Apparently I can not verify the token via REST.
What alternative do I have?
From the Firebase Documentation:
The Firebase Admin SDK has a built-in method for verifying and decoding ID tokens. If the provided ID token has the correct format, is not expired, and is properly signed, the method returns the decoded ID token. You can grab the uid of the user or device from the decoded token.
So, you do not need to worry about someone trying to generate fake tokens.
To verify the token in PHP, as described in the docs Firebase Admin SDK for PHP
Minimal code for verifying the token:
use Kreait\Firebase;
use Firebase\Auth\Token\Exception\InvalidToken;
//create Firebase factory object
//$firebase = (new Firebase\Factory())->create();
//get a token from client
//$idTokenString = 'eyJhbGciOiJSUzI1...';
try {
$verifiedIdToken = $firebase->getAuth()->verifyIdToken($idTokenString);
} catch (InvalidToken $e) {
echo $e->getMessage();
}
$uid = $verifiedIdToken->getClaim('sub');
$user = $firebase->getAuth()->getUser($uid);
echo $user;

Retrieving Facebook FanPage insights in a cron

I'm trying to create a cron job with a php script for retrieving info about stats of a Fan Pages and I have some questions:
have I to log a user to get the access token and use the Facebook API?
Which kind of token must to use? App token? Page Token?
I've read in several posts in Stackoverflow that only the Page Access token is necessary, but I have no success:
Request: /419788471442322/?fields=access_token
Response: Unsupported get request.
This is the code
//get the app access token
$facebook->setAccessToken($facebook->getAccessToken());
//Format the api call
$fields = array('access_token');
$page_info = $facebook->getInsights($id,"",$fields);
//display the result
print_r($page_info);
public function getInsights($id, $nameapi, $fields = array(), $limit = null)
{
if (isset($fields)) $fields = implode(",",$fields);
if (isset($limit)) $limit = "&limit=".$limit;
try {
echo '/'.$id.'/'.$nameapi.'?fields='.$fields.$limit;
$fbdata = $this->facebook->api('/'.$id.'/'.$nameapi.'?fields='.$fields.$limit);
} catch (FacebookApiException $e) {
$fbdata = $e->getMessage();
}
return $fbdata;
}
By default, the App Access Token will be used and you don´t need to set it with setAccessToken.
The App Access Token is good enough for basic infos and the Page feed, but for getting access to the Insights you need a Page Access Token and that´s a bit more complicated. Actually, in a Cron Job you would need a Page Access Token that is valid forever, basic ones are only valid for 2 hours. "Extended Page Access Token" is exactly what you need.
More info about Access Tokens and how to get an Extended Page Access Token:
https://developers.facebook.com/docs/facebook-login/access-tokens/
http://www.devils-heaven.com/facebook-access-tokens/

OAuthException: An active access token must be used to query information about the current user

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;
}

Categories