Grails REST安全性-将用户ID添加到令牌 [英] Grails REST security - Add user id to token

查看:163
本文介绍了Grails REST安全性-将用户ID添加到令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将用户ID字段添加到/api/login返回的令牌中

I want to add user id field to token returned from /api/login

当前是:

{
    "username": "user",
    "roles": [
        "ROLE_USER"
    ],
    "token_type": "Bearer",
    "access_token": "eyJhbGciOiJIUzI1NiJ9.2uk2YoHsyd7bqUdtUYN19ef..",
    "expires_in": 3600,
    "refresh_token": "eyJhbGciOiJIUzI1NiJ9.eyJwcmluY2lwYWwiOiJINH.."
}

我需要:

{
    "id": "1",
    "username": "user",
    "roles": [
        "ROLE_USER"
    ],
    "token_type": "Bearer",
    "access_token": "eyJhbGciOiJIUzI1NiJ9.2uk2YoHsyd7bqUdtUYN19ef..",
    "expires_in": 3600,
    "refresh_token": "eyJhbGciOiJIUzI1NiJ9.eyJwcmluY2lwYWwiOiJINH.."
}

目标-使用用户ID(例如POST/api/something)进行查询 还有其他方法吗? 预先感谢

the target - queries with user id, like POST /api/something Is there any other approaches? Thanks in advance

推荐答案

您还没有提到Grails版本,所以我要发布为Grails 2.4.4实现的答案

You have not mentioned the Grails version, so I am posting the answer which I have implemented for Grails 2.4.4

首先,您需要在src/groovy下创建的自定义类中实现AccessTokenJsonRenderer接口,如下所示.

1st thing you need to implement the AccessTokenJsonRenderer interface in your custom class created under src/groovy like below.

import grails.plugin.springsecurity.SpringSecurityUtils
import grails.plugin.springsecurity.rest.token.AccessToken
import grails.plugin.springsecurity.rest.token.rendering.AccessTokenJsonRenderer
import groovy.json.JsonBuilder
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.GrantedAuthority

/**
 * Created by Prakash Thete on 17/04/2018
 */
class CustomAppRestAuthTokenJsonRenderer implements AccessTokenJsonRenderer  {

    @Override
    String generateJson(AccessToken accessToken){

        // Add extra custom parameters if you want in this map to be rendered in login response
        Map response = [
                id           : accessToken.principal.id,
                username     : accessToken.principal.username,
                access_token : accessToken.accessToken,
                token_type   : "Bearer",
                refresh_token: accessToken.refreshToken,
                roles        : accessToken.authorities.collect { GrantedAuthority role -> role.authority }
        ]

        return new JsonBuilder( response ).toPrettyString()
    }
}

第二步,您需要在resources.groovy中创建我们的自定义类的bean,如下所示

2nd thing you need to create the bean of our custom class in resources.groovy, like below

// For overriding the token json renderer
accessTokenJsonRenderer(CustomAppRestAuthTokenJsonRenderer)

现在,点击api/login后,您将收到用户ID以及其他详细信息.

Now after hitting the api/login you will receive the id of the user along with the other details.

希望这会有所帮助!

这篇关于Grails REST安全性-将用户ID添加到令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆