我正在使用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获取用户名?
答案 0 :(得分:0)
我能够找出问题所在。
这是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"
而不是{{1 }}。
这个问题有一个类似的问题:Override UserAuthenticationConverter for JWT OAuth Tokens。我能够使用他们的解决方案并根据自己的需要进行更改。我还决定使用jwt中的"username"
代替sub
。