如果您想在Auth-JSON响应中添加关于用户的更多详细信息,您可以使用主体ID和用户查询,如下所示。
请注意添加了@Transactional注释。
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()
}
}
您想向响应中添加什么并不重要,通过用户对象,您几乎可以添加任何内容。只是不要试图进行太多的查询,因为这将导致登录过程非常缓慢。