Spring Oauth2获取当前用户对象

时间:2018-03-08 19:45:52

标签: spring spring-boot spring-security spring-security-oauth2

我正在使用Spring 5 Oauth2。 我可以看到当前有效的令牌。

Collection<OAuth2AccessToken> tokens = tokenStore.findTokensByClientId("clientIdPassword");
    if (tokens != null) {
        for (OAuth2AccessToken token : tokens) {
            tokenValues.add(token.getValue());
        }
    }

上面的代码块显示了客户端ID为clientIdPassword的有效令牌,但我想只获取当前记录的用户对象。我试过了Authentication authentication = SecurityContextHolder.getContext().getAuthentication();,但它返回了匿名用户。有没有办法获得唯一当前记录的用户对象?

2 个答案:

答案 0 :(得分:0)

通常,您的代码是获取当前登录用户对象的正确方法。
如果您想查找其他方式,请参阅此处:http://www.baeldung.com/get-user-in-spring-security

答案 1 :(得分:0)

在您的令牌服务中,您可以添加OAuth2Authentication类作为参数

 @RequestMapping(method = RequestMethod.POST, value = "/oauth/token/revokeById/{tokenId}")
    @ResponseBody
    public void revokeToken(HttpServletRequest request, @PathVariable String tokenId,OAuth2Authentication auth) {

Springboot会自动将登录的用户详细信息映射到此对象。现在,您可以执行以下操作来访问用户名

auth.getPrincipal().toString()
相关问题