OAuth 2.0 using Grails Part – 1

13 / May / 2014 by pulkit 3 comments

Following steps need to be followed for OAuth 2.0 authentication :

(1) Obtain OAuth 2.0 credentials from the Google Developers Console:



First you need to have a google account. create a project at Google Developers Console after logging into your Google account. Click on the project name go to “APIs and auth” click on credentianls and then create a client ID. You will get client id and client secret which is required for OAuth 2.0 authentication . You also need to add Javascript origin and redirect URI’s by clicking on edit settings.

Let us assume javascript origin is “http://localhost:8080/”
and redirect URI is “http://localhost:8080/TestOAuth/google/success”

(2) Get authorization code.



First you need to obtain authorization code in order to get the access token.
You need to have a link where a user can click to initiate the process of OAuth 2.0
The link should be as follows:


<a href="https://accounts.google.com/o/oauth2/auth?redirect_uri=http%3A%2F%2Flocalhost:8080%2FTestOAuth%2Fgoogle%2Fsuccess
 & 
response_type=code 
& 
client_id={your client id} 
& 
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile 
& 
approval_prompt=force 
& 
access_type=offline"> SignInWithGoogle </a>

After clicking on the above link you need to login using google account . After logging in you will be redirected to “http://localhost:8080/TestOAuth/google/success?code={authorization code}”

You can get the authorization code token from Querystring

(3) Exchange authorization code for access token



Place the following line in BuildConfig.groovy

plugins {
runtime ":rest:0.7"
}

This plugin is required to make Get and POST Requests

In the GoogleController.groovy we need to have a success action as follows:

def success(String code) {
        String googleaccesstoken = ""
        JSONObject googleJsonResponseForAccessToken
        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 = 1

            response.success = { resp, json ->
                println "POST response status: ${resp.statusLine}"
                googleJsonResponseForAccessToken = json
                googleaccesstoken = json.access_token
            }
        }

}

In the above code we are making a POST request to https://accounts.google.com/o/oauth2/token and in response we will get following json

{
"access_token": {access_token},
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": {refresh_token},
"id_token": {id_token}
}

This response is stored in json object of response.success method in the above code . we have stored the value of access_token in variable “googleaccesstoken” in the code above.

(4) Get UserInfo from access_token



To get the information of the user you need to make following request:

JSONObject userInfo
http.request(GET) {
            uri.path = "https://www.googleapis.com/userinfo/v2/me"
            uri.query = [accesstoken:googleaccesstoken]
            headers.'Authorization'="Bearer ${googleaccesstoken}"
            response.success = { resp, json ->
                println "Get response status: ${resp.statusLine}"
                userInfo=json
            }
        }
       render "User Name  ::  "+userInfo.name
       render "User Id  ::  "+userInfo.id

In the above code we have used the access_token which we got from the json response in step (3)

FOUND THIS USEFUL? SHARE IT

comments (3)

  1. Neha Khanna

    Hello,
    I am able to get authorization code, however in second step to get access token, I am getting error message:

    groovyx.net.http.HttpResponseException: Bad Request
    at groovyx.net.http.HTTPBuilder.defaultFailureHandler(HTTPBuilder.java:636)
    at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:492)
    at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:427)
    at groovyx.net.http.HTTPBuilder.request(HTTPBuilder.java:359)
    at GoogleController$_closure2$$EP9oOWa0.doCall(Google.groovy:77)
    at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:195)
    at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)

    Could you please help me see what I will be doing wrong?
    If you could send me your GoogleController.groovy, that would be great.

    THanks

    Neha

    Reply

Leave a comment -