OAuth 2.0 using Grails Part – 2

22 / Jun / 2014 by pulkit 0 comments

Obtain accessToken from refreshToken

In the previous article OAuth 2.0 using Grails Part – 1 I have given a detailed explanation regarding user authentication using OAuth 2.0. In this article i will explain how you can obtain access_token from the refresh_token. Please refer to step(3) of part – 1 of this article where we obtained a JSON of the following format :

[java]
{
"access_token": {access_token},
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": {refresh_token},
"id_token": {id_token}
}
[/java]

You need to persist the refresh_token in some database because access_token which we have got in the JSON is only valid for 1 hour. A fresh access_token can be obtained with the help of refresh_token. Following method will take persisted refresh_token as a parameter and will return a fresh access_token.

[java]
String getLatestAccessToken(String refreshToken) {
String latestToken = ""
def http = new HTTPBuilder(‘http://localhost:8080/’)
http.request(POST) {
uri.path = ‘https://accounts.google.com/o/oauth2/token’
requestContentType = "application/x-www-form-urlencoded"
body = [
client_id: "{Client ID}",
client_secret: "{Client Secret}",
grant_type: "refresh_token",
refresh_token: refreshToken
]
response.success = { resp, json ->
latestToken = json.access_token
}
}
return latestToken
}
[/java]

In the above code response.success closure contains parameter json which contains the response in the following format:

[java]
{
"access_token": {access_token},
"token_type": "Bearer",
"expires_in": 3600,
"id_token": {id_token}
}
[/java]

From this JSON we are obtaining access_token which is again valid for 1 hour only.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *