此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Authorization Server 1.4.2spring-doc.cadn.net.cn

作方法:在 JWT 访问令牌中将颁发机构添加为自定义声明

本指南演示如何向 JWT 访问令牌添加资源所有者权限。 术语“权限”可能表示不同的形式,例如资源所有者的角色、权限或组。spring-doc.cadn.net.cn

为了使资源所有者的权限可用于资源服务器,我们将自定义声明添加到访问令牌中。 当客户端使用访问令牌访问受保护的资源时,资源服务器将能够获取有关资源所有者的访问级别以及其他潜在用途和好处的信息。spring-doc.cadn.net.cn

向 JWT 访问令牌添加自定义声明

您可以使用OAuth2TokenCustomizer<JWTEncodingContext> @Bean. 请注意,此@Bean只能定义一次,因此必须小心确保您自定义的是适当的令牌类型 — 在本例中为 Access Token。 如果您有兴趣自定义 ID 令牌,请参阅 User Info Mapper 指南以了解更多信息。spring-doc.cadn.net.cn

以下是向访问令牌添加自定义声明的示例,换句话说,授权服务器颁发的每个访问令牌都将填充自定义声明。spring-doc.cadn.net.cn

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.spring-doc.cadn.net.cn

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.spring-doc.cadn.net.cn

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
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;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

@Configuration
public class CustomClaimsWithAuthoritiesConfiguration {
	@Bean
	public UserDetailsService users() {
		UserDetails user = User.withDefaultPasswordEncoder()
				.username("user1") (1)
				.password("password")
				.roles("user", "admin") (2)
				.build();
		return new InMemoryUserDetailsManager(user);
	}

	@Bean
	public OAuth2TokenCustomizer<JwtEncodingContext> jwtTokenCustomizer() { (3)
		return (context) -> {
			if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) { (4)
				context.getClaims().claims((claims) -> { (5)
					Set<String> roles = AuthorityUtils.authorityListToSet(context.getPrincipal().getAuthorities())
							.stream()
							.map(c -> c.replaceFirst("^ROLE_", ""))
							.collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); (6)
					claims.put("roles", roles); (7)
				});
			}
		};
	}
}
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.spring-doc.cadn.net.cn