Gmail API: permanent token access - php

After many researches I can now retrieve my Gmail inbox with my PHP code. Now I want to know if it's possible to get a permanent token access for the API without being forced to log in with OAuth.
I'm making a small application that would retrieve 3 different Gmail inboxes and people who would work with my app won't waste their time authorizing my Gmail app to the different inboxes.
I mean, is there a way to avoid authorizing each time I try to retrieve my Gmail inbox like a permanent token access I'll get just once then store it into my database?
Thanks for your help.

No such thing as permanent token, but there's refresh token:
Handling authorization
requests
Exchange the authorization code for an access token
The authorization code is a one-time code that your server can
exchange for an access token. This access token is passed to the Gmail
API to grant your application access to user data for a limited time.
If your application requires offline access, the first time your app
exchanges the authorization code, it also receives a refresh token
that it uses to receive a new access token after a previous token has
expired. Your application stores this refresh token (generally in a
database on your server) for later use.
Important: Always store user refresh tokens. If your application needs
a new refresh token it must send a request with the approval_prompt
query parameter set to force. This will cause the user to see a dialog
to grant permission to your application again.
Here's a snippet from the Gmail API Quickstart
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}

Related

How to keep user logged in once token get expired?

I have created an api in PHP, using JWT. I have set 10 minute expiration time for tokens. How can I verify if user is still logged in after 10 minutes?
Like OAuth providing refresh token along with access token and using refresh token we can generate new access token. But I found that The JWT standard does not have any concept of a "refresh token" or "access token". in one of git thread.
My JWTHandler function to create token:
public function jwtEncodeData($iss, $data)
{
$this->token = array(
//Adding the identifier to the token (who issue the token)
"iss" => $iss,
"aud" => $iss,
// Adding the current timestamp to the token, for identifying that when the token was issued.
"iat" => $this->issuedAt,
// Token expiration
"exp" => $this->expire,
// Payload
"data" => $data
);
$this->jwt = JWT::encode($this->token, $this->jwt_secrect, 'HS256');
return $this->jwt;
}
It is just returning token, any way to create refresh token in JWT? Or I should create it with plain PHP which may contain user id? So, if client receive Invalid token error they can request new token with that user id in refresh token.
Updated:
I have found here Before making any API call, the mobile app checks if the token is about to expire (with the help of the stored values). If the token is about to expire, the app sends the refresh token which instructs the server to generate a new access token but my mobile app(android) developer saying that they have never checked if token valid or not in their past experience. How does it should actually carried out? If I check token is valid or not in API and than create new token if not valid previous one, than I need to send new generated token to mobile app in response? And mobile app needs to check each API response if token is there in response?
I have set 10 minute expiration time for tokens. How can I verify if user is still logged in after 10 minutes?
Access tokens are disconnected from user sessions. The lifetime of an access token has nothing to do with a user's session. It seems to me that in your setup you should rather be using plain old sessions instead of access and refresh tokens.
But I found that The JWT standard does not have any concept of a "refresh token" or "access token". in one of git thread.
That is true because the JWT standard only tells you what a JSON Web Token should look like, how it can be signed for integrity protection (through the JWS standard), and how it can be encrypted for privacy (through the JWE standard). JWTs can be used for many different purposes, and access and refresh tokens are just one such purpose.
any way to create refresh token in JWT
JWT is not a framework that you can use to create refresh tokens automatically, consume them, etc. OAuth and OpenID Connect are standards that define how to deal with access and refresh tokens (what are the flows which allow you to issue those tokens, and how to properly refresh access tokens). You can have a look at the refresh grant from OAuth. It describes what you need. Basically, you need to issue another token (it may be a JWT) and send both to the client. When the client needs to refresh the access token, it sends the refresh token to a special endpoint and gets a new access token (if the refresh token is valid).
Again, in your case, I feel that implementing OAuth refresh flow will be a bit of an overkill, and I would definitely have a look at sessions.
How does it should actually carried out? If I check token is valid or not in API and than create new token if not valid previous one, than I need to send new generated token to mobile app in response? And mobile app needs to check each API response if token is there in response?
It's not exactly accurate. You should validate the token in your API. If the token is expired (or invalid for other reasons), the API should respond with a 401 response. This is a sign to the mobile app that the token is no longer valid and that it needs a new one. If the app has a refresh token, then it can use that token to get a new access token. The mobile app can now call your API again, with a new access token. If the app doesn't have access to a refresh token, or if the refresh token is expired, then the app should ask the user to log in again.
you need to look at the OpenID Connect (OIDC) protocol, which defines how refresh token, id token, & access token work together.

How to get permanent access token for microsoft outlook api

I have set scopes as follows:
openid profile
offline_access
User.Read Mail.ReadWrite
Mail.Send
Calendars.ReadWrite
Contacts.Read
I want a permanent access token so that I don't need to login again and again.
Help me out, how can I use a token in the login api to get permanent access?
Thanks in advance.
Graph API provides two authentication flow:
1. Get access on behalf of a user
2. Get access without a user
If you want to run the Outlook API in background service(not all app need user signed-in, based on actual demand), you can use the authentication flow #2. By using this way, end user do not need to request Token explicitly, so it look like permanent access token, until the Microsoft/Azure need the admin consent again.
If you want to run the Outlook API just for signed-in user, you can use the authentication flow #1. After get an access Token, store the access Token and Refresh Token in the Token-cache and use the refresh Token to request new Token while the access token lifetime expires. If both access/refresh token have expired, the user need to sign-in again to re-grant permission.

PHP Console Application with OAuth 2.0 Refresh Tokens, how to store?

I am working on a PHP project that utilizes the API from a few services. For a single API, it uses OAuth 2.0 authorization to authenticate the application's API access. However, I am unsure how I should approach the process to authenticate a local console application.
I would not be using a webflow to authenticate the API, as my PHP script runs in a local console. The API allows for the retrieving of the access token and refresh token by entering my username and password (they recommend this only for console applications).
Once I get the access token, I may use it to make API requests. This works fine. However, I am unsure what to do with my refresh token. The API consumes refresh tokens as such:
/oauth2/access_token/ (Refresh token usage)
Context: Client's Web Server
Required arguments: refresh_token, grant_type=refresh_token,
client_id, client_secret
Access token scope: None
On success, a JSON response is returned to the client:
{
"access_token": a valid access token,
"scope": scope as given in authorize,
"expires_in": seconds to expiry,
"refresh_token": a token that can be used to get a new access token
}
Consuming a refresh token will immediately expire the related access
token. Refresh tokens are single-use. A new refresh token is returned
from this call, ready for consumption later.
From what I gather from this, my authentication process should be something like this:
Initial authentication - pass username/password via environment variable, get the access/refresh token from response
Store the refresh token? Check for the expiry of the initial access token
If initial access token has expired, pull refresh token from file and make a request for a new access/refresh token
Store new refresh token?
Does this sound like the correct authentication flow? Is there a specific way I should be storing the refresh token? I am aware there may be a lot of security concerns for simply storing the refresh token in a text file, as it has the ability to give complete access to my account. Are there any better alternatives?
Thanks!
Authentication flow is fine. For more detailing and validation, you can read https://www.rfc-editor.org/rfc/rfc6749 .
You can store ‘Refresh token’ either in file or db using encryption key and this MUST only be transmitted using TLS. ‘Refresh token’ is used in senerios where server do want to some scheduled background activities like accessing of profile and related data from other oAuth server based on previous stored access token without asking user name and password again over and again. If in case ‘Access token’ is invalidated then ‘Refresh token’ will be used to get new ‘Access token’ to serve purpose.

Facebook RTU Access Token

When my callback URL it's called by facebook, I'm getting a new access token:
$this->facebook->getAccessToken();
But, the generated access token is invalid. I noticed that the generated token it's my APP_ID|APP_SECRET
How can I generate a valid access token to use on a RTU? (I want to get the user's wall).
if you are receiving RTU from facebook and want to get information from graph api your server side previously should store long-term access_token for user. And this access_token should have correct permissions.
So the flow is next:
User loged-in to your app.
Your server should store long-term access_token from here
Your server receives RTU from facebook, where you are using previously saved long-term access token for creating session for requests.
It won't work in another way.

Google API Authentication for server

I've been trying to get Google's Calendar API working in a PHP web application, but I'm having a hard time getting authenticated.
What I want to do is to allow users to interact with calendars of a single account known by the server.
Each type of scenario covered in the OAuth 2.0 docs talks about "user consent" which involves a login form and the individual user logging in, but I want the server itself to authenticate directly and obtain an access token for itself.
Is there some part of OAuth or some alternative mechanism I can use to do this?
In order to do this, you must go through the steps for user consent and then copy the access tokens it gives you into the PHP code.
The usual procedure for OAuth is like this:
Send user to authentication page.
User comes back with $_GET['code']
Send $_GET['code'] to OAuth server for a token
Store token in database for the user (or session, if it's very short lived)
But when doing it with a single calendar like this, you modify step 4. Instead, you dump the token to screen and copy it into your PHP file as variables, instead of putting it in the database. Then when you go to pass the access token to the server, you just pass the known, static token rather than a dynamic token from the database / session.
See mathewh's answer here:
How to automate login to Google API to get OAuth 2.0 token to access known user account
The lightbulb for me is when you get the access token you get a refresh_token as well... you use this token to "refresh" your access token once it expires.
There is no way around a manual authorization step the first time.

Categories