【问题标题】:OAuth2Authentication.getPrincipal() returns client_id instead of usernameOAuth2Authentication.getPrincipal() 返回 client_id 而不是用户名
【发布时间】:2019-07-22 05:14:31
【问题描述】:

我正在使用 spring-security-oauth2-autoconfigure 版本 2.1.6.RELEASE 来保护资源服务器,并尝试获取我的 jwt 中列出的用户名。我的 jwt 的有效负载包含 client_id 和用户名。当我尝试从 OAuth2Authentication 对象获取 Principal 时,它返回 client_id 而不是用户名。

例如,如果 jwt 有效负载包含:

client_id":"2v3r098kgipu053lph0cb9nfjb","username":"7e953975-0df2-49ff-9b23-cae0864384b7" 

我的代码是:

@GetMapping("/whoami")
public String whoami(@CurrentSecurityContext OAuth2Authentication auth) {
    logger.debug("auth.name: {}", auth.getName() );
    logger.debug("auth.principal: {}", auth.getPrincipal());
    OAuth2Request req = auth.getOAuth2Request();
    logger.debug("req.clientid: {}", req.getClientId() );
    return "success";
}

我在日志中看到以下内容:

auth.name: 2v3r098kgipu053lph0cb9nfjb  
auth.principal: 2v3r098kgipu053lph0cb9nfjb  
req.clientid: 2v3r098kgipu053lph0cb9nfjb

我需要做什么才能从 jwt 获取用户名?

【问题讨论】:

  • 刚试了一下,返回null

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


【解决方案1】:

我能够找出问题所在。

这是OAuth2Authentication.getPrincipal() 方法:

public Object getPrincipal() {
        return this.userAuthentication == null ? this.storedRequest.getClientId() : this.userAuthentication
                .getPrincipal();
    }

auth.getUserAuthentication() 返回 null 所以这解释了我看到的结果。

this.userAuthentication 为 null 的原因是因为 DefaultUserAuthenticationConverter.extractAuthentication(Map<String, ?> map) 方法试图将主体设置为 map.get(USERNAME),其中映射是 jwt 和 USERNAME = "user_name",而不是 "username"

这个问题有类似的问题:Override UserAuthenticationConverter for JWT OAuth Tokens。我能够使用他们的解决方案并根据我的需要进行更改。我还决定使用 jwt 中的 sub 而不是 username

【讨论】:

    猜你喜欢
    • 2021-05-07
    • 2019-08-08
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多