Automatic refresh of expired credentials.

921 views
Skip to first unread message

jakub...@pmedianetwork.com

unread,
Mar 25, 2014, 10:55:50 AM3/25/14
to adwor...@googlegroups.com
Hi!
I need an offline access to AdWords API. 
I've obtained a refresh token with the help of GoogleAuthorizationCodeFlow with 'offline' access type as described here: https://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow.
I'm saving the refreshToken in a DB for future use.
With the refresh token I'm able to get a credential with this statement:

Credential credential = new OfflineCredentials.Builder()
                .forApi(OfflineCredentials.Api.ADWORDS)
                .fromFile()
                .withRefreshToken(specificRefresToken)
                .build()
                .generateCredential()

The problem I'm facing is that the credential expires after 1 hour. 
In the documentation it states ' By default, our client libraries automatically refresh an expired access token.'  Which utility do I need to use to get this functionality?
To play fair, after the credential is initialized I'm putting it into a pool so for the next AdWords API request I can reuse it.
So my getCredential method looks like that (is this additional check for expiration time required?):

        Credential credential = initializedCredentials.get(client.id)
        if (credential != null && credential.expiresInSeconds > 50) {
            return credential
        }
       //initialize credential and put into initializedCredentials for future use
       ....

I wouldn't like to reinvent a wheel if there are some utilities already available and  can handle this for me.
I appreciate the feedback.

Cheers!

Michael Cloonan (AdWords API Team)

unread,
Mar 28, 2014, 9:14:16 AM3/28/14
to adwor...@googlegroups.com, jakub...@pmedianetwork.com
Hi,

You don't need to store the Credential in a pool for re-use. It will automatically re-use the existing access token for as long as it's valid, and then fetch a new one if it's invalid, every time you create the Credential object. It's intended to work this way so you instantiate a new Credential object whenever you need one. Access tokens are expected to expire after a short amount of time (one hour), for greater security.

I suppose if you wanted to optimize things further and use a pool of Credential objects, you would just have to have logic that recognizes expired ones and replaces them with fresh ones whenever you receive this message.

Regards,
Mike, AdWords API Advisor
Reply all
Reply to author
Forward
0 new messages