Junfeng Li
Junfeng Li

Reputation: 131

Grails spring security rest inject tokenGenerator

I have a similar requirement like this post mentioned. :REST spring security - Manually authenticating a new user and getting access token

According to the accepted answer, the codes will be like:

class RegisterController {

    def springSecurityService
    def tokenGenerator
    def tokenStorageService

    def register() {
         //do stuff
         springSecurityService.reauthenticate(username)
         String tokenValue = tokenGenerator.generateToken()
         tokenStorageService.storeToken(tokenValue, springSecurityService.principal)

         redirect url: "http://example.org/?access_token=${tokenValue}"
    } 
}

I tried but it didn't work for me. It seems the TokenGenerator implementation class is not injected right. I understand the default implementation in grails-spring-security-rest TokenGenerator will be the JWT but wonder where should I register or config it.

Upvotes: 0

Views: 896

Answers (1)

Prakash Thete
Prakash Thete

Reputation: 3892

Well if you want to use the "tokenGenerator" then you need to register it under the "resources.groovy" like below

// creating the bean of token generator
tokenGenerator(SecureRandomTokenGenerator)

and then inject it into your controller or service like below

class RegisterController {

def springSecurityService
def tokenGenerator
def tokenStorageService

    def register() {
         //do stuff
         springSecurityService.reauthenticate(username)
         String tokenValue = tokenGenerator.generateToken()
         tokenStorageService.storeToken(tokenValue, springSecurityService.principal)

         redirect url: "http://example.org/?access_token=${tokenValue}"
    }
}

I have followed the same example (with slight modification) and its working as expected.

I have used the "userDetailsService" for generating user instance instead of "springSecurityService.reauthenticate(username)"

So my function looks like below.

/**
 * For generating the access token for the user
 *
 * @param userName : Holds the username of the user
 *
 * @return : access token
 */
String generateAccessToken(String userName){
    String tokenValue

    try{
        //load user details
        def userDetails = userDetailsService.loadUserByUsername(userName)

        //generate access token
        tokenValue = tokenGenerator.generateAccessToken(userDetails).accessToken

        //store access token
        tokenStorageService.storeToken(tokenValue, userDetails)
    } catch (Exception e){
       //Exception handling code
    }

    return tokenValue
}

Upvotes: 1

Related Questions