How To Access GSP Pages of Grails Using JWT

Posted By : Winkle Jindal | 30-Apr-2018
JWT  by default set authentication Token in the header with response But GSP pages in grails always take token from cookies. So for using GSP pages, we have to send Token in the cookie.
 
Step for authenticating a user in grails 2.4.4 using JWT token and accessing GSP pages
 
1. we have to override the Token Reader class of Rest security which set Token  in the header.
 
(/Jwt-Demo/src/groovy/com/oodles/jwtToken/JwtCookieTokenReader.groovy)
            
package com.Jwt-Demo.jwtToken

import grails.plugin.springsecurity.rest.token.AccessToken
import grails.plugin.springsecurity.rest.token.reader.TokenReader
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j

import javax.servlet.http.Cookie
import javax.servlet.http.HttpServletRequest

@Slf4j
@CompileStatic
class JwtCookieTokenReader implements TokenReader {

	final static String DEFAULT_COOKIE_NAME = 'JWT'

	String cookieName = DEFAULT_COOKIE_NAME

	@Override
	AccessToken findToken(HttpServletRequest request) {
		println("request"
			+ request)
		   println("jeelefknvk,")
		log.debug "Looking for jwt token in a cookie named {}", cookieName
		String tokenValue = null
		Cookie cookie = request.getCookies()?.find { Cookie cookie -> cookie.name.equalsIgnoreCase(cookieName) }
		//println("kerjg"+cookie.name)
		
		if ( cookie ) {
			tokenValue = cookie.value
		}

		log.debug "Token: ${tokenValue}"
		return tokenValue ? new AccessToken(tokenValue) : null

	}
}    
        
 
 
JwtCookieTokenReader overrides the functionality of TokenReader. It will take Token from the cookie authenticate it and send JWT token in response cookies.
 
 
2.Now register it in grails-app/conf/spring/resources.groovyas.tokenReader.
 
              import demo.JwtCookieTokenReader
import grails.plugin.springsecurity.rest.token.reader.TokenReader
beans = {
	tokenReader(JwtCookieTokenReader) {
		cookieName = 'jwt'
	}
}
  
        
 
 
3. Now configure Grails Spring Security Rest Plugin in config.groovy :
 
           grails {
        plugin {
                springsecurity {
                        rest {
                                token {
                                        validation {
                                                useBearerToken = false 
                                                enableAnonymousAccess = true 
                                        }
                                        storage {
                                                jwt {
                                                        secret = 'foobar123'*4 
                                                }
                                        }
                                }
                                oauth {
                                        frontendCallbackUrl = { String tokenValue -> "http://localhost:8080/auth/success?token=${tokenValue}" } 
                                       
                                }
                        }
                     
                }
        }
}
     
        
 
4.  Make an API in  Auth Controller which  set  token in the cookie after Login so that all the @secured API can get JWT token in cookie request 
 
              package demo
import grails.plugin.springsecurity.annotation.Secured
import groovy.util.logging.Slf4j
import grails.plugin.springsecurity.rest.token.reader.TokenReader

import javax.servlet.http.Cookie

import org.codehaus.groovy.grails.plugins.support.aware.GrailsConfigurationAware

@Slf4j
class AuthController implements GrailsConfigurationAware {

    TokenReader tokenReader

    int jwtExpiration

    String grailsServerUrl

    static allowedMethods = [
            success: 'GET',
            logout: 'POST'
    ]

    @Secured('permitAll')
    def success(String token) {
		println("insde succes"+token)
        log.debug('token value {}', token)
        if (token) {
            Cookie cookie = jwtCookie(token)
            response.addCookie(cookie) 
        }
        [grailsServerUrl: grailsServerUrl]
    }

    protected Cookie jwtCookie(String tokenValue) {
        Cookie jwtCookie = new Cookie( cookieName(), tokenValue )
        jwtCookie.maxAge = 3600
        jwtCookie.path = '/'
        jwtCookie.setHttpOnly(true) 
        if ( httpOnly() ) {
            jwtCookie.setSecure(true) 
        }
        jwtCookie
    }

	@Override
	public void setConfiguration(ConfigObject co) {
		println("sijdh"+co.getProperty('grails.plugin.springsecurity.rest.token.storage.memcached.expiration'))
		//jwtExpiration =
		grailsServerUrl = co.getProperty('grails.serverURL')
		
	}

    protected boolean httpOnly() {
        grailsServerUrl?.startsWith('https')
    }

    protected String cookieName() {
        if ( tokenReader instanceof JwtCookieTokenReader ) {
            return ((JwtCookieTokenReader) tokenReader).cookieName  
        }
        return 'jwt'
    }

	
	
}  
        

About Author

Author Image
Winkle Jindal

Winkle is masters in computer application.She is currently working as Java Developer. she is quick learner and always passionate to learn new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..