Can you reuse a Google service account access token? - oauth

Using the Google API PHP Client with a service account, it returns an array like the following:
array (size=3)
'access_token' => string '...TOKEN...' (length=127)
'token_type' => string 'Bearer' (length=6)
'expires_in' => int 3600
Is it best practice to generate a new token every page request? It seems wasteful to do so when each token is valid for one hour. But since the token does not include a created value or a token_id value, the builtin isAccessTokenExpired() method will always return true, meaning it is always expired.
I see several options for reusing the same token:
Option 1: When token is created via fetchAccessTokenWithAssertion(), I can manually add a created value to the token array with time() as its value. Then save that to session/database so later when isAccessTokenExpired is called it will have that field to verify.
Option 2: Save token to session/database along with the timestamp the token will expire (time() + $token['expires_in']), and then on subsequent views I can do my own calculations to verify that the token is still in a valid time period. This seems a bit weird too though as I can't be fully sure that Google has not revoked the token or anything funny like that.
Option 3: Call a method that uses the access token and checks its response. If the call succeeded then the access token must be good still, if not then I can go ahead and ask for a new one. But what method could I call? One that would only need the most basic permissions would be good.
Thank you.

You can request a new token each time, but it's needless overhead and I believe it can eat into your API call quota as well.
I basically do #2, but I also subtract 10 seconds off of the expires_in just to be certain I don't have a request made with a just-expired token. TBH there's no reason that Google would revoke an individual token that wouldn't result in full revocation of all access, that's kind of why their token lifetime is so short to begin with.
I don't use the official API client, but the Cliff's Notes version of my logic is:
class Token {
public function __construct($info) {
$this->token = $info['access_token'];
$this->type = $info['token_type'];
$this->expiry = time() + $info['expires_in'] - 10;
}
public function isValid() {
return ($this->validFor()) > 0;
}
public function validFor() {
return $this->expiry - time();
}
}
class TokenFactory implements TokenFactoryInterface {
public function token($force_new=false) {
if( $force_new || !isset($this->token) || !$this->token->isValid() ) {
$this->token = $this->newToken();
}
return $this->token;
}
}

Related

Google Identity: what is the recommended way to get a new access token after it expires

I am getting an access token like this:
private async _promptForToken(scopes: string[], prompt: "none" | "consent"): Promise<string> {
const that = this
return new Promise(resolve => {
const tokenClient = google.accounts.oauth2.initTokenClient({
client_id: this.clientId,
scope: scopes.join(' '),
callback: function (tokenResponse) {
that._storeTokenResponse(tokenResponse)
resolve(tokenResponse.access_token)
}
})
tokenClient.requestAccessToken({prompt})
})
}
I storing the token in local storage. If I leave the browser for an hour, so the access token expires, and I come back to my app and click a button that requires a new access token, I am requesting the new token using this code:
this._promptForToken(scopes, 'none')
In other words, I am asking for the same access permissions, but without consent. When I do that I get back a response like this:
{error_subtype: "access_denied", error: "interaction_required"}
Which I can't find documented anywhere, but that's another issue.
If instead, I ask for a new access token using consent i.e.
this._promptForToken(scopes, 'consent')
The Google dialog box for permissions pops up for a second, then disappears, which is horrible UX. And this will happen every time an access token expires. Horrible I say!
What is the recommended way to request a new access token?
Context: browser only, so implicit flow only, I do not want to have to maintain refresh tokens in the backend.

Expire-date in refresh-token (oauth2, exact)

So I'm using the exact-online XML-api to retrieve some user-related data.
This works fine so far, but since it is using oauth 2.0, I am being redirected after 600 sec and the login-prompt appears again.
This function refreshes the access-token:
/**
* #param string $refreshToken
* #return array {access_token, expires_in, refresh_token}
*/
public function refreshAccessToken($refreshToken)
{
$params = array(
'refresh_token' => $refreshToken,
'grant_type' => self::GRANT_REFRESH_TOKEN,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
);
$url = sprintf(self::URL_TOKEN, $this->countryCode);
return $this->getResponse($url, $params);
}
I debuged into it and the expires_in is set to 600. I guess this is the cause I'm being logged after after a short amount. My question: how can I disable this 600 sec timeout?
Also I found this function:
/**
* #param int $expiresInTime
*/
protected function setExpiresIn($expiresInTime)
{
$this->expiresIn = time() + $expiresInTime;
}
I modified the function and added a *1000 so it doesn't run out, but that didn't affect the outcome.
Is this an oauth-specific thing? Is it somehow managable to don't be kicked off after 10 mins?
There is no such thing in the backend of exact-online, which could change this value. Also, since this is a request I recieve, I don't think I can manipulate it, right?
Update 1
Due to the good feedback, I think I got a start with that problem, but no solution yet. I'll provide the code I'm currently using. I also asked the support of exact, but didn't got too much help there unfortunatly.
Please see this code:
<?php
require_once($sShopHomeDir . "modules/" . $sModulePath . "/library//exact/ExactApi.php");
$this->_exactApi = new ExactApi('de', $this->_sClientId, $this->_sClientSecret, $this->_sDivision);
$this->_exactApi->getOAuthClient()->setRedirectUri($this->_sRedirectUri.$param);
if (!isset($_GET['code']))
{
// Redirect to Auth-endpoint
$authUrl = $this->_exactApi->getOAuthClient()->getAuthenticationUrl();
header('Location: ' . $authUrl, true, 302);
die('Redirect');
}
else
{
$tokenResult = $this->_exactApi->getOAuthClient()->getAccessToken($_GET['code']);
$this->_exactApi->setRefreshToken($tokenResult['refresh_token']);
}
From the comments and answer, I'm convinced that this is the way to go. I'm retrieving a code and store/set the refresh-token - which, from my understanding, is correct that way.
For a better readabilty, I'll provide links to the two files which Exact online provides in their examples:
ExactApi.php
ExactOAuth.php
You have two OAuth flows supported by Exact Online. From the information and the timeout you give I am pretty sure you are using the implicit grant flow, which is not documented by Exact, but it does work.
The only other option you have is to use the token based authentication flow, which requires an extra step, namely exchanging your response code for an access token. That token is valid for a year and can be refreshed afterwards to extend the period for another year. The token based authentication flow is only useful in environments you can control, like web applications.
That token based authentication flow doesn't work with two phase authentication, so you can't refresh a token after that one year period.

Google realtime Model update onFileLoad

I see that the workflow is to start authrorizer, giving it file loader. So, we have a sequence of callbacks, onAuthrorized => start loading file => doc.getModel() on file load. Here they say how you get the model. But, I also see that gapi.drive.realtime.load(fileId, onFileLoaded, initializeModel, handleErrors) can elso end up with TOKEN_REFRESH_REQUIRED and it seems that TOKEN_REFRESH_REQUIRED can fire after the document is loaded, after some time of user inactivity, which seems to be related with token expiration. How should re-authorization to go? Should I tell the client that the current model that he is connected to is invalid? Please note that my app starts on file load. So, if I go the whole stack re-authorization, which calls another file load, which calls another document loaded will re-start my application. Is it supposed way to go? To put in other words, is there a way to refresh the token without loosing existing connection?
Where is the token stored actually? I do not see that I receive it on authorized. It is not passed to the realtime.load. How does realtime.load knows about the token? How can I speed up the token expiration for debug?
I am still not sure that this is a right answer but this is what I have got looking at code here, which says that we should provide empty callback to re-authorize
/**
* Reauthorize the client with no callback (used for authorization failure).
* #param onAuthComplete {Function} to call once authorization has completed.
*/
rtclient.Authorizer.prototype.authorize = function(onAuthComplete) {
function authorize() {
gapi.auth.authorize({client_id: rtclient.id, scope: ['install', 'file'],}, handleAuthResult)
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
hideAuthorizationButton() && onAuthComplete()
} else with (authorizationButton) {
display = 'block' ;
onclick = authorize;
}
}
You call it first use it in a function to load your document
(rtclient.authorizer ? rtclient.authorizer = identity : rtclient.authorize) (proceedToLoadingTheFile)
But later, on timeout we have code
function handleErrors(e) { with(gapi.drive.realtime.ErrorType) {switch(e.type) {
case TOKEN_REFRESH_REQUIRED: rtclient.authorizer.authorize() ; break
case CLIENT_ERROR: ...
Note no arguemnts in the latter. Authorizer won't reload the document. I think that this explains the logic asked. However, it does not answer about the internals, how is it possible that loader takes on existing authorizer or switches to a new one.

Google Oauth - TokenVerifier How to USE?

I'm trying to use Google OAuth with Sign in & Sign Up for my Web Server Application.
This is the page : https://developers.google.com/identity/sign-in/web/backend-auth that I have referenced, but I am stuck in using the Google Client API, the TokenVerifier that is mentioned below in the document. I tried to find some examples, but I couldn't find one, as I am not sure how to handle the parameters in the methods that the sample shows.
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
...
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
.setAudience(Arrays.asList(CLIENT_ID))
.build();
// (Receive idTokenString by HTTPS POST)
GoogleIdToken idToken = verifier.verify(idTokenString);
if (idToken != null) {
Payload payload = idToken.getPayload();
if (payload.getHostedDomain().equals(APPS_DOMAIN_NAME)
// If multiple clients access the backend server:
&& Arrays.asList(ANDROID_CLIENT_ID, IOS_CLIENT_ID).contains(payload.getAuthorizedParty())) {
System.out.println("User ID: " + payload.getSubject());
} else {
System.out.println("Invalid ID token.");
}
} else {
System.out.println("Invalid ID token.");
}
For example, I know what these CLIENT_ID, ANDROID_CLIENT_ID, IOS_CLIENT_ID parameters mean in the sample code(in the reference page), but the server only receives id_token, which is basically a String Text. (That was made by the google api in the client-side, the javascript)
So, I do not have these parameter values passed to the server from the client. I know that google shows another way: the tokeninfo endpoint, but they mentioned that it is for only 100user/month only. (If I translated it correctly) However, for the tokeninfo endpoint way, they return the JSON file of containing client ids, which I think that would be the values for the parameters that I mentioned before, but I do not want to use the token info endpoint method.
So, my question is, how do I get the right parameter values for the sample code that is showed in the google document page? I only receive id_token value from the client.
ANDROID_CLIENT_ID or IOS_CLIENT_ID should be hard coded (in a config file) in your server's code.
Essentially your server is getting an id_token in a request and you need to make sure if it is meant for your app or server by checking the audience in there and making sure it matches one of the values you are expecting.

Multiple Twitter accounts using Google App Script

I'm experimenting with Google Apps Script and Twitter, and I'd like to be able to access multiple Twitter accounts through one spreadsheet. At the moment I've attempted the approach below (a unique OAuthService name for each Twitter account), and this kind-of works but it clunky because I have to randomly authorize one account (and not more than one) each time the script is run, and the popup dialog doesn't tell me which account (i.e. id) I'm authenticating for.
Ideally, I'd like to force each user to give Twitter permission on first use, then store that token for later use - is this possible withe Google App Script?
Thanks.
function oAuth(id) {
var oauthConfig = UrlFetchApp.addOAuthService(NS_TWITTER + id);
oauthConfig.setAccessTokenUrl("https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl("https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(CONSUMER_KEY);
oauthConfig.setConsumerSecret(CONSUMER_SECRET);
};
and then
var options =
{
"method": "GET",
"oAuthServiceName":NS_TWITTER + id,
"oAuthUseToken":"always",
};
try {
var result = UrlFetchApp.fetch(feed, options);
}
Yes, is possible.
To store the token values use userProperties (Docs here) or CacheService wich remains for 20 minutes in cache (Docs here).
Example storing token using UserProperties
UserProperties.setProperty('token', 'value');
var token = UserProperties.getProperty('token');
Example storing token using CachService
// Gets a cache that is private to the current user
var cache = CacheService.getPrivateCache();
cache.put('token', 'value');
var token = cache.get('token');
After building you cache solution you need to check if the token is valid with twitter API. If it's invalid you should require the auth again.

Resources