对于最新的稳定版本,请使用 Spring Authorization Server 1.4.2! |
作方法:在 JWT 访问令牌中将颁发机构添加为自定义声明
本指南演示如何向 JWT 访问令牌添加资源所有者权限。 术语“权限”可能表示不同的形式,例如资源所有者的角色、权限或组。
为了使资源所有者的权限可用于资源服务器,我们将自定义声明添加到访问令牌中。 当客户端使用访问令牌访问受保护的资源时,资源服务器将能够获取有关资源所有者的访问级别以及其他潜在用途和好处的信息。
向 JWT 访问令牌添加自定义声明
您可以使用OAuth2TokenCustomizer<JWTEncodingContext>
@Bean
.
请注意,此@Bean
只能定义一次,因此必须小心确保您自定义的是适当的令牌类型 — 在本例中为 Access Token。
如果您有兴趣自定义 ID 令牌,请参阅 User Info Mapper 指南以了解更多信息。
以下是向访问令牌添加自定义声明的示例,换句话说,授权服务器颁发的每个访问令牌都将填充自定义声明。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.token.JwtEncodingContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;
@Configuration
public class CustomClaimsConfiguration {
@Bean
public OAuth2TokenCustomizer<JwtEncodingContext> jwtTokenCustomizer() {
return (context) -> {
if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
context.getClaims().claims((claims) -> {
claims.put("claim-1", "value-1");
claims.put("claim-2", "value-2");
});
}
};
}
}
Add authorities as custom claims to JWT access tokens
To add authorities of the resource owner to a JWT access token, we can refer to the custom claim mapping method above and populate a custom claim with the authorities of the Principal
.
We define a sample user with a set of authorities for demonstration purposes, and populate a custom claim in the access token with those authorities.
1
Define a sample user user1
with an in-memory UserDetailsService
.
2
Assign the roles for user1
.
3
Define an OAuth2TokenCustomizer<JwtEncodingContext>
@Bean
that allows for customizing the JWT claims.
4
Check whether the JWT is an access token.
5
Access the default claims via the JwtEncodingContext
.
6
Extract the roles from the Principal
object. The role information is stored as a string prefixed with ROLE_
, so we strip the prefix here.
7
Set the custom claim roles
to the set of roles collected from the previous step.
As a result of this customization, authorities information about the user will be included as a custom claim in the access token.