Microsoft Graph API won't work in production - php

I have my site set up so I can use Oauth for single sign on and added access to be able to post calendar entries made on my site to the user's outlook calendar.
Everything works on my dev environment but when I go to my calendar page in production it throws this error:
https://graph.microsoft.com/v1.0/me/calendarsresulted in a401 Unauthorized` response: { "error": { "code": "InvalidAuthenticationToken", "message": "Access token validation failure."
I am using the same token I get from oAuth for the calendars. Is that not the right way to do it? And if not how do I go about the right way to do it and why would it work?
here is a part of my oauth page
// Get an access token using the authorization code grant
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
$_SESSION['refresh_token'] =$accessToken->getRefreshToken();
$graph = new Graph();
$graph->setAccessToken($accessToken);
//the sesion token for calendars expires faster than our token to stay in connect, so if it expires have the user sign back in
try {
$user = $graph->createRequest("GET", "/me/calendars")
->execute();
} catch (Exception $e) { //FAILS HERE
// sessionTimeout(); exit;
var_dump($e);
}
EDIT
throwing the token i get back into JWT I see that when in development my token has all the information including about what scopes i have. But in production the token is missing the "scp" field. I have no idea what I am doing wrong.
EDIT 2
I thought maybe I would need a refresh token but that still gives me the same error.

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();

"unauthorized_client" error when using PHP client to refreshToken with Google API client?

I am requesting access to the user's data from an IOS app using this code from the GoogleSignIn pod
[GIDSignIn sharedInstance].uiDelegate = self;
[[GIDSignIn sharedInstance] setScopes:#[ ... ];
[[GIDSignIn sharedInstance] signInSilently];
I then receive the accessToken and the refreshToken in the appDelegate and I send that to the server running PHP and using this google client library (https://github.com/googleapis/google-api-php-client) ... for the first hour everything is working fine and the access token is valid and allowing me access to all the scopes. Then after an hour the access token expires and I try to refresh it using this code
$client = new Google_Client();
$client->setApplicationName(<app name>);
$client->setDeveloperKey(<google_oauth_developer_key>);
$client->setClientSecret(<google_oauth_client_secret>);
$client->setClientId(<google_oauth_client_id>);
$client->refreshToken("1/12ju3ZZim-r6co195lIVNNvzBq9x5G64GJCWkYsOQ18");
and the "refreshToken" function above returns this error
=> [
"error" => "unauthorized_client",
"error_description" => "Unauthorized",
]
It's worth noting that the app name, google_oauth_developer_key, google_oauth_client_secret, and google_oauth_client_id have not changed. They are the same ones that were working earlier to retrieve the user's contacts, calendar events, etc when the access token was not yet expired.
What could be causing this error?
You need to actually use your refresh token at some point.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->getAccessToken();
Code ripped from my Oauth2Authentication.php sample
Note
Also remember that refresh tokens are user / client based. So if the token was generated by one client then a different client will probably not be able to use it. I will be very surprised if you can use a refresh token created in Ios code in a php application. The client types are different.
Ok so I figured out what I did wrong. I originally followed these instructions https://developers.google.com/identity/sign-in/ios/sign-in which assume you need online access only, but I actually need offline access to the scopes so I followed these instructions https://developers.google.com/identity/sign-in/ios/offline-access and it works now. So instead of having the IOS app send up the access token and the refresh token separately like this
- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user
withError:(NSError *)error {
if (!error) {
NSString *accessToken = user.authentication.accessToken;
NSString *refreshToken = user.authentication.refreshToken;
I simply have it send up the serverAuthCode like this
- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user
withError:(NSError *)error {
if (!error) {
NSString *serverAuthCode = user.serverAuthCode;
and then on the server I run this code to get the access token
$access_token = $client->authenticate($google_server_auth_code);
$client->setAccessToken($access_token);
and then when the access token expires I run this to refresh it
$access_token = $client->refreshToken($client->getRefreshToken());
$client->setAccessToken($access_token);

Google_Auth_Exception: Error refreshing the OAuth2 token

I am trying to fetch user's data from google plus using PHP.
I'm using below tutorial
https://www.youtube.com/watch?v=-65R420rIUA
Situation:
User login into my app android using google plus button i fetch the access token using googleSignInResult.googleSignInAccount.getIdToken()
I send this token to my server which runs php to fetch users data using google php client (as described in the video)
below is my code
try{
$gClient = new Google_Client();
$gClient->setApplicationName('pixyfi');
$gClient->setClientId($config['google']['appid']);
$gClient->setClientSecret($config['google']['secret']);
$token = json_encode(array("access_token"=>$lptoken,"refresh_token"=>$lptoken,"token_type"=>"Bearer","expires_in"=>3600,"id_token"=>$lptoken,"created"=>1320790426));
$gClient->setAccessToken($token);
$gClient->addScope(Google_Service_Plus::PLUS_ME);
$plus = new Google_Service_Plus($gClient);
$gpUserProfile = $plus->people->get('me');
echo "User Fetched as:".$gpUserProfile['id'];
}
catch(Google_Auth_Exception $x){
echo "Error:".$x;
}
But i am getting error:
Error:Google_Auth_Exception: Error refreshing the OAuth2 token, message: '{
"error" : "invalid_client"
}' in /var/www/html/api/auth/vendor/google/apiclient/src/Google/Auth/OAuth2.php:364
Could you please let me know what mistake i am making here?
this is some of my code which handles token thing. Implement this logic and let me know if you are still getting errors.
$row is is fetched from database and contains token information
$client->setAccessToken($row['token']);
if(time()>$row['created']+$row['expires_in'])
{
$client->refreshToken($row['refresh_token']);
$token=$client->getAccessToken();
DB::Query("-----UPDATE DB TOKEN INFO-------");
$client->setAccessToken($token);
}

Check an User token with Facebook API with PHP

I have a web app, where user are signing with facebook, then I save their access token in my database. I'm trying to check if their token are valid with the PHP SDK then if the token is valid , I'd like to extend it.
The problem is that I get an error message which tells me:
(#100) You must provide an app access token or a user access token that is an owner or developer of the app
Does that mean only app dev team member's can have their token extended or verified?
Here is my code:
FacebookSession::setDefaultApplication(
'my_client_id',
'my_client_secret'
);
$session = new FacebookSession($user_token);
try {
$resp = (new FacebookRequest(
$session, 'GET', '/debug_token', array(
'input_token' => $user_token
)
))->execute()->getGraphObject();
//profile ok
} catch(\Exception $exp) {
//profile ko
}
The debug API is for if you want to do things as the app, not as the user.

Google PHP SDK - not getting refresh token

I am trying to get a refresh token for the Google API's, using the PHP SDK. I am authenticating the user with Javascript, retrieving a code, and exchanging it for an access_token server side, but this doesn't grant me an access token. What am I doing wrong? Here is the code I use:
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->addScope('https://www.googleapis.com/auth/plus.me');
$client->addScope('https://www.google.com/m8/feeds');
$client->setRedirectUri('postmessage');
$client->setAccessType('offline');
if (isset($_REQUEST['code'])) {
$client->authenticate($_REQUEST['code']);
if ($client->getAccessToken()) {
$_SESSION['access_token'] = $client->getAccessToken();
$token_data = $client->verifyIdToken()->getAttributes();
$result['data']=$token_data;
$result['access_token']=json_decode($_SESSION['access_token']);
}
}
debug($result); //my own function, var_dumps the content of an array
Here is the result of the array:
$result['access_token'] contains:
access_token: TOKEN
created: 1434380576
expires_in: 3594
id_token: IDTOKEN
token_type:"Bearer"
If I am not mistaken the first access token should also contain the refresh token, what am I doing wrong?
First check the settings in the developer console of Google to see if your RedirectUri is the same and that the API is activated (although if you already got that .json, then I assume it is.
You have to go through the Google Auth Prompt Screen at least 1 time to get a refresh token in your .json, and if your RedirectUri is taking you nowhere, you won't be able to get your refresh token or even the access validated.
You can also try a service account if you're doing small file transactions and don't need a user validation for the process of your script. Good Luck.
The problem was that I had to specify that I want offline access in the authentication process, the client side... The Google API's are horribly documented!!!

Categories