If you want to add even more details about the user in your Auth JSON response, you can use the principal ID and query for the user as follows.
Notice the addition of the @Transactional annotation.
import grails.gorm.transactions.Transactional
import grails.plugin.springsecurity.rest.token.AccessToken
import grails.plugin.springsecurity.rest.token.rendering.AccessTokenJsonRenderer
import groovy.json.JsonBuilder
import org.springframework.security.core.GrantedAuthority
@Transactional
class CustomAuthTokenRenderer implements AccessTokenJsonRenderer {
@Override
String generateJson(AccessToken accessToken) {
// User the principal ID to get an instance of the user from the database
User user = User.get accessToken.principal.id as Long
// Add extra custom parameters if you want in this map to be rendered in login response
Map res = [
id : user.id,
username : user.username,
firstName : user.firstName,
lastName : user.lastName,
profilePicture : user.profilePicture,
dateOfBirth : user.dob,
expiration : accessToken.expiration,
access_token : accessToken.accessToken,
token_type : "Bearer",
refresh_token : accessToken.refreshToken,
roles : accessToken.authorities.collect { GrantedAuthority role -> role.authority },
friends: user.friends.collect { Friend friend ->
[
id : friend.id,
firstName : friend.firstName,
dateCreated : friend.dateCreated,
lastUpdated : friend.lastUpdated,
]
}
]
return new JsonBuilder(res).toPrettyString()
}
}
It doesn't matter what you want to add to the response, with the user object, you can add almost anything. Just don't be tempted to make too many queries as this will result in a very slow login process.