Santhosh
Santhosh

Reputation: 335

How to get an access token using a refresh token in Java?

I am currently implementing Contact Application using Google Contact API in Java. I have completed steps of authorization and obtained an access token and a refresh token.

Now I have the CLIENT_ID , CLIENT_SECRET AND REFRESH_TOKEN with me . But the access token is getting expired within an hour.

Can someone tell how to automatically generate an access token using a refresh token in Java?

Upvotes: 5

Views: 13767

Answers (2)

Sriram Umapthy
Sriram Umapthy

Reputation: 700

You can use Google OAuth2 client library for getting a new access token using a refresh token.

Here is my code for getting a new access token:

public TokenResponse refreshAccessToken(String refreshToken) throws IOException {
    TokenResponse response = new GoogleRefreshTokenRequest(
            new NetHttpTransport(),
            new JacksonFactory(),
            refreshToken, 
            "your clientId",
            "your clientSecret")
            .execute();
    System.out.println("Access token: " + response.getAccessToken());

    return response;
}

For more information read the official Google API guide:

Upvotes: 7

Dev
Dev

Reputation: 378

I have implemented this scenario in two ways. Not sure they are the best or not but works well for me.

In both cases you have to store the refresh token along with the email id of the user. Then you have to make a HTTP request in the below format.

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

client_id=**<your_client_id>**&
client_secret=**<your_client_secret>**&
refresh_token=**<refresh_token>**&
grant_type=refresh_token

It will return the access_token and expires_in Source

Now the question is how and when to do the http request. So for that I have two ways.

1st one

Store the emailid,refresh token, access token and the current time+3600 seconds. In your database you can schedule to check the expire time in every 5 min and if current time of any user is going to reach(before 5 or 10 min) the expire time, get the refresh token and update the value for that particular user. And during api call just fetch the access token of the user.

2nd one

When user do login in your site, get the access token and current time+ 3600secs and store it in browser cookies. Now before doing any api call just check whether the current time(time when api call is done) is less than the expire time(stored in cookie). If its true then you can use the previous access token else get a new one and again update the cookie. Also you have to put another condition that if the cookie is not present at all then also you have to get new refresh token.

Upvotes: 1

Related Questions