OAuth2Authentication.getPrincipal() returns client_id 而不是用户名
OAuth2Authentication.getPrincipal() returns client_id instead of username
我正在使用 spring-security-oauth2-autoconfigure 版本 2.1。6.RELEASE 来保护资源服务器并尝试获取我的 jwt 中列出的用户名。我的 jwt 的有效负载包含 client_id 和用户名。当我尝试从 OAuth2Authentication
对象获取主体时,它 returns 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 中获取用户名?
我能够弄清楚这个问题。
这是OAuth2Authentication.getPrincipal()
方法:
public Object getPrincipal() {
return this.userAuthentication == null ? this.storedRequest.getClientId() : this.userAuthentication
.getPrincipal();
}
auth.getUserAuthentication()
returns null 所以这解释了我看到的结果。
this.userAuthentication
为 null 的原因是因为 DefaultUserAuthenticationConverter.extractAuthentication(Map<String, ?> map)
方法试图将主体设置为 map.get(USERNAME)
,其中映射是 jwt 而 USERNAME = "user_name"
而不是 "username"
。
这个问题有一个类似的问题:。我能够使用他们的解决方案并根据我的需要对其进行更改。我还决定使用 jwt 中的 sub
而不是 username
.
我正在使用 spring-security-oauth2-autoconfigure 版本 2.1。6.RELEASE 来保护资源服务器并尝试获取我的 jwt 中列出的用户名。我的 jwt 的有效负载包含 client_id 和用户名。当我尝试从 OAuth2Authentication
对象获取主体时,它 returns 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 中获取用户名?
我能够弄清楚这个问题。
这是OAuth2Authentication.getPrincipal()
方法:
public Object getPrincipal() {
return this.userAuthentication == null ? this.storedRequest.getClientId() : this.userAuthentication
.getPrincipal();
}
auth.getUserAuthentication()
returns null 所以这解释了我看到的结果。
this.userAuthentication
为 null 的原因是因为 DefaultUserAuthenticationConverter.extractAuthentication(Map<String, ?> map)
方法试图将主体设置为 map.get(USERNAME)
,其中映射是 jwt 而 USERNAME = "user_name"
而不是 "username"
。
这个问题有一个类似的问题:sub
而不是 username
.