OAuth 2.0 资源服务器 JWT
JWT 的最小依赖项
大多数资源服务器支持功能都集中于 spring-security-oauth2-resource-server
中。然而,解码和验证 JWT 的支持位于 spring-security-oauth2-jose
中,这意味着为了使支持 JWT 编码的承载令牌的资源服务器正常工作,两者都是必需的。
JWT的最小配置
在使用 Spring Boot 时,将应用程序配置为资源服务器包括两个基本步骤。首先,包含所需的依赖项,其次,指定授权服务器的位置。
指定授权服务器
在 Spring Boot 应用程序中,要指定使用哪个授权服务器,只需执行以下操作:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://idp.example.com/issuer
其中 [idp.example.com/issuer](https://idp.example.com/issuer)
是授权服务器将要颁发的 JWT 令牌中 iss
声明所包含的值。资源服务器将使用此属性进一步自我配置,发现授权服务器的公钥,并随后验证传入的 JWT。
要使用 issuer-uri
属性,还必须满足以下条件之一:[idp.example.com/issuer/.well-known/openid-configuration](https://idp.example.com/issuer/.well-known/openid-configuration)
、[idp.example.com/.well-known/openid-configuration/issuer](https://idp.example.com/.well-known/openid-configuration/issuer)
或 [idp.example.com/.well-known/oauth-authorization-server/issuer](https://idp.example.com/.well-known/oauth-authorization-server/issuer)
是授权服务器支持的端点。此端点被称为 Provider Configuration 端点或 Authorization Server Metadata 端点。
就这样!
启动预期
当使用此属性和这些依赖项时,资源服务器将自动配置自身以验证JWT编码的Bearer令牌。
它通过一个确定性的启动过程来实现这一点:
-
查询提供商配置或授权服务器元数据端点以获取
jwks_url
属性 -
查询
jwks_url
端点以获取支持的算法 -
配置验证策略以查询
jwks_url
以获取找到的算法的有效公钥 -
配置验证策略,将每个 JWT 的
iss
声明与[idp.example.com](https://idp.example.com)
进行验证。
这一过程的结果是,授权服务器必须启动并能够接收请求,以便资源服务器成功启动。
如果授权服务器在资源服务器查询时(给定适当的超时时间)宕机,则启动将失败。
运行时预期
一旦应用程序启动,资源服务器将尝试处理任何包含 Authorization: Bearer
头的请求:
GET / HTTP/1.1
Authorization: Bearer some-token-value # Resource Server will process this
只要指定了此方案,资源服务器就会尝试根据Bearer Token规范处理请求。
给定一个格式良好的JWT,资源服务器将会:
-
在启动时从
jwks_url
端点获取公钥,并根据该公钥验证其签名,与 JWT 进行匹配 -
验证 JWT 的
exp
和nbf
时间戳以及 JWT 的iss
声明,以及 -
将每个范围映射到带有前缀
SCOPE_
的权限。
当授权服务器提供新的密钥时,Spring Security 会自动轮换用于验证 JWT 的密钥。
生成的 Authentication#getPrincipal
默认是一个 Spring Security 的 Jwt
对象,而 Authentication#getName
对应于 JWT 中的 sub
属性(如果存在的话)。
从这里开始,可以考虑跳转到:
JWT 认证的工作原理
接下来,让我们看看 Spring Security 用来支持基于 servlet 的应用程序(如我们刚刚看到的)中的 JWT 身份验证的架构组件。
JwtAuthenticationProvider 是一个 AuthenticationProvider 实现,它利用 JwtDecoder 和 JwtAuthenticationConverter 来验证 JWT。
让我们来看看 JwtAuthenticationProvider
在 Spring Security 中是如何工作的。该图解释了 Reading the Bearer Token 中的图表里的 AuthenticationManager 的工作细节。
图 1. JwtAuthenticationProvider
用法
1 从读取 Bearer Token 中的认证 Filter
会将一个 BearerTokenAuthenticationToken
传递给由 ProviderManager 实现的 AuthenticationManager
。
2 ProviderManager
被配置为使用类型为 JwtAuthenticationProvider
的 AuthenticationProvider。
3 JwtAuthenticationProvider
使用 JwtDecoder 对 Jwt
进行解码、验证和校验。
4 JwtAuthenticationProvider
然后使用 JwtAuthenticationConverter 将 Jwt
转换为已授予权限的 Collection
。
5 当认证成功时,返回的Authentication 类型为 JwtAuthenticationToken
,并且其主体是配置的 JwtDecoder
返回的 Jwt
。最终,返回的 JwtAuthenticationToken
将由认证 Filter
设置到 SecurityContextHolder 中。
直接指定授权服务器 JWK 集合 URI
如果授权服务器不支持任何配置端点,或者资源服务器必须能够独立于授权服务器启动,则也可以提供 jwk-set-uri
:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://idp.example.com
jwk-set-uri: https://idp.example.com/.well-known/jwks.json
JWK 集合 uri 没有标准化,但通常可以在授权服务器的文档中找到
因此,资源服务器在启动时不会 ping 授权服务器。我们仍然指定 issuer-uri
,以便资源服务器仍然验证传入 JWT 中的 iss
声明。
此属性也可以直接在DSL中提供。
提供受众
正如已经看到的,issuer-uri 属性验证 iss 声明;这是发送 JWT 的实体。
Boot 也有 audiences
属性用于验证 aud
声明;这是 JWT 发送给的对象。
资源服务器的受众可以如下所示进行指示:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://idp.example.com
audiences: https://my-resource-server.example.com
如果需要,您也可以通过编程方式添加 aud 验证。
结果将是,如果 JWT 的 iss
声明不是 [idp.example.com](https://idp.example.com)
,并且其 aud
声明的列表中不包含 [my-resource-server.example.com](https://my-resource-server.example.com)
,则验证将失败。
覆盖或替换启动自动配置
Spring Boot 为资源服务器生成了两个 @Bean
。
第一个是将应用配置为资源服务器的 SecurityFilterChain
。当包含 spring-security-oauth2-jose
时,这个 SecurityFilterChain
看起来像这样:
- Java
- Kotlin
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
)
.oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeRequests {
authorize(anyRequest, authenticated)
}
oauth2ResourceServer {
jwt { }
}
}
return http.build()
}
如果应用程序没有暴露 SecurityFilterChain
bean,那么 Spring Boot 将会暴露上述默认的 SecurityFilterChain
。
替换这个就像在应用程序中暴露 bean 一样简单:
- Java
- Kotlin
import static org.springframework.security.oauth2.core.authorization.OAuth2AuthorizationManagers.hasScope;
@Configuration
@EnableWebSecurity
public class MyCustomSecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/messages/**").access(hasScope("message:read"))
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt
.jwtAuthenticationConverter(myConverter())
)
);
return http.build();
}
}
import org.springframework.security.oauth2.core.authorization.OAuth2AuthorizationManagers.hasScope
@Configuration
@EnableWebSecurity
class MyCustomSecurityConfiguration {
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeRequests {
authorize("/messages/**", hasScope("message:read"))
authorize(anyRequest, authenticated)
}
oauth2ResourceServer {
jwt {
jwtAuthenticationConverter = myConverter()
}
}
}
return http.build()
}
}
上述要求对于任何以 /messages/
开头的 URL 都需要 message:read
的作用域。
oauth2ResourceServer
DSL 中的方法也将覆盖或替换自动配置。
例如,Spring Boot 创建的第二个 @Bean
是 JwtDecoder
,它将字符串令牌解码为已验证的 Jwt 实例:
- Java
- Kotlin
@Bean
public JwtDecoder jwtDecoder() {
return JwtDecoders.fromIssuerLocation(issuerUri);
}
@Bean
fun jwtDecoder(): JwtDecoder {
return JwtDecoders.fromIssuerLocation(issuerUri)
}
调用 JwtDecoders#fromIssuerLocation 会触发 Provider Configuration 或 Authorization Server Metadata 端点,以便推导出 JWK Set Uri。
如果应用程序没有暴露一个 JwtDecoder
bean,那么 Spring Boot 将会暴露上述默认的 JwtDecoder
。
并且可以使用 jwkSetUri()
覆写其配置,或者使用 decoder()
替换。
或者,如果你根本没使用 Spring Boot,那么这两个组件 —— 过滤器链和 JwtDecoder
可以在 XML 中指定。
过滤链指定如下:
- Xml
<http>
<intercept-uri pattern="/**" access="authenticated"/>
<oauth2-resource-server>
<jwt decoder-ref="jwtDecoder"/>
</oauth2-resource-server>
</http>
并且 JwtDecoder
如下所示:
- Xml
<bean id="jwtDecoder"
class="org.springframework.security.oauth2.jwt.JwtDecoders"
factory-method="fromIssuerLocation">
<constructor-arg value="${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}"/>
</bean>
使用 jwkSetUri()
授权服务器的 JWK 集合 URI 可以作为配置属性进行配置,也可以在 DSL 中提供:
- Java
- Kotlin
- Xml
@Configuration
@EnableWebSecurity
public class DirectlyConfiguredJwkSetUri {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt
.jwkSetUri("https://idp.example.com/.well-known/jwks.json")
)
);
return http.build();
}
}
@Configuration
@EnableWebSecurity
class DirectlyConfiguredJwkSetUri {
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeRequests {
authorize(anyRequest, authenticated)
}
oauth2ResourceServer {
jwt {
jwkSetUri = "https://idp.example.com/.well-known/jwks.json"
}
}
}
return http.build()
}
}
<http>
<intercept-uri pattern="/**" access="authenticated"/>
<oauth2-resource-server>
<jwt jwk-set-uri="https://idp.example.com/.well-known/jwks.json"/>
</oauth2-resource-server>
</http>
使用 jwkSetUri()
优先于任何配置属性。
使用 decoder()
比 jwkSetUri()
更强大的是 decoder()
,它将完全替换 JwtDecoder 的任何 Boot 自动配置:
- Java
- Kotlin
- Xml
@Configuration
@EnableWebSecurity
public class DirectlyConfiguredJwtDecoder {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt
.decoder(myCustomDecoder())
)
);
return http.build();
}
}
@Configuration
@EnableWebSecurity
class DirectlyConfiguredJwtDecoder {
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeRequests {
authorize(anyRequest, authenticated)
}
oauth2ResourceServer {
jwt {
jwtDecoder = myCustomDecoder()
}
}
}
return http.build()
}
}
<http>
<intercept-uri pattern="/**" access="authenticated"/>
<oauth2-resource-server>
<jwt decoder-ref="myCustomDecoder"/>
</oauth2-resource-server>
</http>
暴露一个 JwtDecoder
@Bean
或者,暴露一个 JwtDecoder @Bean
与 decoder()
具有相同的效果。你可以使用 jwkSetUri
构造它,如下所示:
- Java
- Kotlin
@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
}
@Bean
fun jwtDecoder(): JwtDecoder {
return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()
}
或者你可以使用颁发者,并让 NimbusJwtDecoder
在调用 build()
时查找 jwkSetUri
,如下所示:
- Java
- Kotlin
@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withIssuerLocation(issuer).build();
}
@Bean
fun jwtDecoder(): JwtDecoder {
return NimbusJwtDecoder.withIssuerLocation(issuer).build()
}
或者,如果默认设置适合你,你也可以使用 JwtDecoders
,它除了配置解码器的验证器之外,还执行了上述操作:
- Java
- Kotlin
@Bean
public JwtDecoders jwtDecoder() {
return JwtDecoders.fromIssuerLocation(issuer);
}
@Bean
fun jwtDecoder(): JwtDecoders {
return JwtDecoders.fromIssuerLocation(issuer)
}
配置可信算法
默认情况下,NimbusJwtDecoder
(因此资源服务器)将只使用RS256
信任和验证令牌。
您可以通Spring Boot、the NimbusJwtDecoder 构建器或从JWK 集合响应来定制它。
通过 Spring Boot
设置算法的最简单方法是将其作为属性:
spring:
security:
oauth2:
resourceserver:
jwt:
jws-algorithms: RS512
jwk-set-uri: https://idp.example.org/.well-known/jwks.json
使用构建器
不过,为了获得更大的功能,我们可以使用随 NimbusJwtDecoder
一起提供的构建器:
- Java
- Kotlin
@Bean
JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withIssuerLocation(this.issuer)
.jwsAlgorithm(RS512).build();
}
@Bean
fun jwtDecoder(): JwtDecoder {
return NimbusJwtDecoder.withIssuerLocation(this.issuer)
.jwsAlgorithm(RS512).build()
}
多次调用 jwsAlgorithm
会配置 NimbusJwtDecoder
信任多个算法,如下所示:
- Java
- Kotlin
@Bean
JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withIssuerLocation(this.issuer)
.jwsAlgorithm(RS512).jwsAlgorithm(ES512).build();
}
@Bean
fun jwtDecoder(): JwtDecoder {
return NimbusJwtDecoder.withIssuerLocation(this.issuer)
.jwsAlgorithm(RS512).jwsAlgorithm(ES512).build()
}
或者,你可以调用 jwsAlgorithms
:
- Java
- Kotlin
@Bean
JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withIssuerLocation(this.issuer)
.jwsAlgorithms(algorithms -> {
algorithms.add(RS512);
algorithms.add(ES512);
}).build();
}
@Bean
fun jwtDecoder(): JwtDecoder {
return NimbusJwtDecoder.withIssuerLocation(this.issuer)
.jwsAlgorithms {
it.add(RS512)
it.add(ES512)
}.build()
}
从 JWK 集响应
由于 Spring Security 的 JWT 支持是基于 Nimbus 的,你也可以使用它的所有强大功能。
例如,Nimbus 有一个 JWSKeySelector
实现,它将根据 JWK Set URI 响应选择算法集。你可以使用它来生成一个 NimbusJwtDecoder
,如下所示:
- Java
- Kotlin
@Bean
public JwtDecoder jwtDecoder() {
// makes a request to the JWK Set endpoint
JWSKeySelector<SecurityContext> jwsKeySelector =
JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(this.jwkSetUrl);
DefaultJWTProcessor<SecurityContext> jwtProcessor =
new DefaultJWTProcessor<>();
jwtProcessor.setJWSKeySelector(jwsKeySelector);
return new NimbusJwtDecoder(jwtProcessor);
}
@Bean
fun jwtDecoder(): JwtDecoder {
// makes a request to the JWK Set endpoint
val jwsKeySelector: JWSKeySelector<SecurityContext> = JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL<SecurityContext>(this.jwkSetUrl)
val jwtProcessor: DefaultJWTProcessor<SecurityContext> = DefaultJWTProcessor()
jwtProcessor.jwsKeySelector = jwsKeySelector
return NimbusJwtDecoder(jwtProcessor)
}
信任单个非对称密钥
使用硬编码的RSA公钥比通过JWK Set端点支持资源服务器要简单。可以通过Spring Boot或使用构建器来提供公钥。
通过 Spring Boot
通过Spring Boot指定密钥非常简单。可以像这样指定密钥的位置:
spring:
security:
oauth2:
resourceserver:
jwt:
public-key-location: classpath:my-key.pub
或者,为了实现更复杂的查找,你可以对 RsaKeyConversionServicePostProcessor
进行后处理:
- Java
- Kotlin
@Bean
BeanFactoryPostProcessor conversionServiceCustomizer() {
return beanFactory ->
beanFactory.getBean(RsaKeyConversionServicePostProcessor.class)
.setResourceLoader(new CustomResourceLoader());
}
@Bean
fun conversionServiceCustomizer(): BeanFactoryPostProcessor {
return BeanFactoryPostProcessor { beanFactory ->
beanFactory.getBean<RsaKeyConversionServicePostProcessor>()
.setResourceLoader(CustomResourceLoader())
}
}
指定密钥的位置:
key.location: hfds://my-key.pub
然后自动注入该值:
- Java
- Kotlin
@Value("${key.location}")
RSAPublicKey key;
@Value("\${key.location}")
val key: RSAPublicKey? = null
使用构建器
要直接配置一个 RSAPublicKey
,你可以简单地使用适当的 NimbusJwtDecoder
构建器,如下所示:
- Java
- Kotlin
@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(this.key).build();
}
@Bean
fun jwtDecoder(): JwtDecoder {
return NimbusJwtDecoder.withPublicKey(this.key).build()
}
信任单个对称密钥
使用单一的对称密钥也很简单。你可以简单地加载你的 SecretKey
,并使用相应的 NimbusJwtDecoder
构造器,如下所示:
- Java
- Kotlin
@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withSecretKey(this.key).build();
}
@Bean
fun jwtDecoder(): JwtDecoder {
return NimbusJwtDecoder.withSecretKey(key).build()
}
配置授权
由OAuth 2.0授权服务器颁发的JWT通常会有一个scope
或scp
属性,表示它被授予的范围(或权限),例如:
{ …, "scope" : "messages contacts"}
在这种情况下,资源服务器会尝试将这些范围强制转换为授权列表,并在每个范围前加上字符串 "SCOPE_".
这意味着,要使用从 JWT 派生的范围来保护端点或方法,相应的表达式应包含此前缀:
- Java
- Kotlin
- Xml
import static org.springframework.security.oauth2.core.authorization.OAuth2AuthorizationManagers.hasScope;
@Configuration
@EnableWebSecurity
public class DirectlyConfiguredJwkSetUri {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/contacts/**").access(hasScope("contacts"))
.requestMatchers("/messages/**").access(hasScope("messages"))
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(Customizer.withDefaults())
);
return http.build();
}
}
import org.springframework.security.oauth2.core.authorization.OAuth2AuthorizationManagers.hasScope;
@Configuration
@EnableWebSecurity
class DirectlyConfiguredJwkSetUri {
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeRequests {
authorize("/contacts/**", hasScope("contacts"))
authorize("/messages/**", hasScope("messages"))
authorize(anyRequest, authenticated)
}
oauth2ResourceServer {
jwt { }
}
}
return http.build()
}
}
<http>
<intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
<intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
<oauth2-resource-server>
<jwt jwk-set-uri="https://idp.example.org/.well-known/jwks.json"/>
</oauth2-resource-server>
</http>
或者类似地使用方法安全性:
- Java
- Kotlin
@PreAuthorize("hasAuthority('SCOPE_messages')")
public List<Message> getMessages(...) {}
@PreAuthorize("hasAuthority('SCOPE_messages')")
fun getMessages(): List<Message> { }
手动提取授权
然而,有许多情况下,默认设置是不够的。例如,一些授权服务器不使用 scope
属性,而是有自己的自定义属性。或者,在其他时候,资源服务器可能需要将属性或属性组合转换为内部权限。
为此,Spring Security 提供了 JwtAuthenticationConverter
,它负责将 Jwt 转换为 Authentication。默认情况下,Spring Security 会使用 JwtAuthenticationConverter
的默认实例来连接 JwtAuthenticationProvider
。
作为配置 JwtAuthenticationConverter
的一部分,你可以提供一个子转换器,将 Jwt
转换为已授予权限的 Collection
。
假设你的授权服务器通过一个名为 authorities
的自定义声明来传递权限。在这种情况下,你可以配置 JwtAuthenticationConverter 应该检查的声明,如下所示:
- Java
- Kotlin
- Xml
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
@Bean
fun jwtAuthenticationConverter(): JwtAuthenticationConverter {
val grantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()
grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities")
val jwtAuthenticationConverter = JwtAuthenticationConverter()
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter)
return jwtAuthenticationConverter
}
<http>
<intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
<intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
<oauth2-resource-server>
<jwt jwk-set-uri="https://idp.example.org/.well-known/jwks.json"
jwt-authentication-converter-ref="jwtAuthenticationConverter"/>
</oauth2-resource-server>
</http>
<bean id="jwtAuthenticationConverter"
class="org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter">
<property name="jwtGrantedAuthoritiesConverter" ref="jwtGrantedAuthoritiesConverter"/>
</bean>
<bean id="jwtGrantedAuthoritiesConverter"
class="org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter">
<property name="authoritiesClaimName" value="authorities"/>
</bean>
您还可以配置不同的权限前缀。您可以将每个权限的前缀从 SCOPE_
更改为 ROLE_
,如下所示:
- Java
- Kotlin
- Xml
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
@Bean
fun jwtAuthenticationConverter(): JwtAuthenticationConverter {
val grantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()
grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_")
val jwtAuthenticationConverter = JwtAuthenticationConverter()
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter)
return jwtAuthenticationConverter
}
<http>
<intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
<intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
<oauth2-resource-server>
<jwt jwk-set-uri="https://idp.example.org/.well-known/jwks.json"
jwt-authentication-converter-ref="jwtAuthenticationConverter"/>
</oauth2-resource-server>
</http>
<bean id="jwtAuthenticationConverter"
class="org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter">
<property name="jwtGrantedAuthoritiesConverter" ref="jwtGrantedAuthoritiesConverter"/>
</bean>
<bean id="jwtGrantedAuthoritiesConverter"
class="org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter">
<property name="authorityPrefix" value="ROLE_"/>
</bean>
或者,你可以通过调用 JwtGrantedAuthoritiesConverter#setAuthorityPrefix("")
完全移除前缀。
为了获得更大的灵活性,DSL 支持使用任何实现 Converter<Jwt, AbstractAuthenticationToken>
接口的类来完全替换转换器:
- Java
- Kotlin
static class CustomAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
public AbstractAuthenticationToken convert(Jwt jwt) {
return new CustomAuthenticationToken(jwt);
}
}
// ...
@Configuration
@EnableWebSecurity
public class CustomAuthenticationConverterConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt
.jwtAuthenticationConverter(new CustomAuthenticationConverter())
)
);
return http.build();
}
}
internal class CustomAuthenticationConverter : Converter<Jwt, AbstractAuthenticationToken> {
override fun convert(jwt: Jwt): AbstractAuthenticationToken {
return CustomAuthenticationToken(jwt)
}
}
// ...
@Configuration
@EnableWebSecurity
class CustomAuthenticationConverterConfig {
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeRequests {
authorize(anyRequest, authenticated)
}
oauth2ResourceServer {
jwt {
jwtAuthenticationConverter = CustomAuthenticationConverter()
}
}
}
return http.build()
}
}
配置验证
使用最少的 Spring Boot 配置,指定授权服务器的 issuer uri,资源服务器将默认验证 iss
声明以及 exp
和 nbf
时间戳声明。
在需要自定义验证的情况下,Resource Server 提供了两个标准验证器,并且也接受自定义的 OAuth2TokenValidator
实例。
自定义时间戳验证
JWT 通常具有一个有效期窗口,窗口的开始时间由 nbf
声明指示,结束时间由 exp
声明指示。
然而,每个服务器都可能经历时钟漂移,这会导致一个服务器认为令牌已过期,而另一个服务器却不这么认为。随着分布式系统中协作服务器数量的增加,这可能会导致一些实现上的问题。
资源服务器使用 JwtTimestampValidator
来验证令牌的有效时间窗口,并且可以通过配置 clockSkew
来缓解上述问题:
- Java
- Kotlin
@Bean
JwtDecoder jwtDecoder() {
NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
JwtDecoders.fromIssuerLocation(issuerUri);
OAuth2TokenValidator<Jwt> withClockSkew = new DelegatingOAuth2TokenValidator<>(
new JwtTimestampValidator(Duration.ofSeconds(60)),
new JwtIssuerValidator(issuerUri));
jwtDecoder.setJwtValidator(withClockSkew);
return jwtDecoder;
}
@Bean
fun jwtDecoder(): JwtDecoder {
val jwtDecoder: NimbusJwtDecoder = JwtDecoders.fromIssuerLocation(issuerUri) as NimbusJwtDecoder
val withClockSkew: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(
JwtTimestampValidator(Duration.ofSeconds(60)),
JwtIssuerValidator(issuerUri))
jwtDecoder.setJwtValidator(withClockSkew)
return jwtDecoder
}
默认情况下,Resource Server 配置了 60 秒的时钟偏差。
配置自定义验证器
使用 OAuth2TokenValidator
API 来添加对 aud 声明 的检查非常简单:
- Java
- Kotlin
OAuth2TokenValidator<Jwt> audienceValidator() {
return new JwtClaimValidator<List<String>>(AUD, aud -> aud.contains("messaging"));
}
fun audienceValidator(): OAuth2TokenValidator<Jwt?> {
return JwtClaimValidator<List<String>>(AUD) { aud -> aud.contains("messaging") }
}
或者,为了获得更多的控制,你可以实现你自己的 OAuth2TokenValidator
:
- Java
- Kotlin
static class AudienceValidator implements OAuth2TokenValidator<Jwt> {
OAuth2Error error = new OAuth2Error("custom_code", "Custom error message", null);
@Override
public OAuth2TokenValidatorResult validate(Jwt jwt) {
if (jwt.getAudience().contains("messaging")) {
return OAuth2TokenValidatorResult.success();
} else {
return OAuth2TokenValidatorResult.failure(error);
}
}
}
// ...
OAuth2TokenValidator<Jwt> audienceValidator() {
return new AudienceValidator();
}
internal class AudienceValidator : OAuth2TokenValidator<Jwt> {
var error: OAuth2Error = OAuth2Error("custom_code", "Custom error message", null)
override fun validate(jwt: Jwt): OAuth2TokenValidatorResult {
return if (jwt.audience.contains("messaging")) {
OAuth2TokenValidatorResult.success()
} else {
OAuth2TokenValidatorResult.failure(error)
}
}
}
// ...
fun audienceValidator(): OAuth2TokenValidator<Jwt> {
return AudienceValidator()
}
然后,要添加到资源服务器中,只需要指定 JwtDecoder 实例:
- Java
- Kotlin
@Bean
JwtDecoder jwtDecoder() {
NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
JwtDecoders.fromIssuerLocation(issuerUri);
OAuth2TokenValidator<Jwt> audienceValidator = audienceValidator();
OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);
jwtDecoder.setJwtValidator(withAudience);
return jwtDecoder;
}
@Bean
fun jwtDecoder(): JwtDecoder {
val jwtDecoder: NimbusJwtDecoder = JwtDecoders.fromIssuerLocation(issuerUri) as NimbusJwtDecoder
val audienceValidator = audienceValidator()
val withIssuer: OAuth2TokenValidator<Jwt> = JwtValidators.createDefaultWithIssuer(issuerUri)
val withAudience: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(withIssuer, audienceValidator)
jwtDecoder.setJwtValidator(withAudience)
return jwtDecoder
}
如前所述,你可以选择在 Boot 中配置 aud
验证(见#_supplying_audiences)。
配置声明集映射
Spring Security 使用 Nimbus 库来解析 JWT 并验证其签名。因此,Spring Security 受到 Nimbus 对每个字段值的解释以及如何将其强制转换为 Java 类型的影响。
例如,因为 Nimbus 仍然兼容 Java 7,所以它不使用 Instant
来表示时间戳字段。
而且完全有可能使用不同的库来处理 JWT,这可能需要调整该库自己做出的强制转换决策。
或者,简单地说,资源服务器可能由于特定于域的原因想要向 JWT 添加或移除声明。
出于这些目的,Resource Server 支持使用 MappedJwtClaimSetConverter
映射 JWT 声明集。
自定义单个声明的转换
默认情况下,MappedJwtClaimSetConverter
会尝试将声明强制转换为以下类型:
Claim | Java 类型 |
---|---|
aud | Collection<String> |
exp | Instant |
iat | Instant |
iss | String |
jti | String |
nbf | Instant |
sub | String |
单个声明的转换策略可以使用 MappedJwtClaimSetConverter.withDefaults
进行配置:
- Java
- Kotlin
@Bean
JwtDecoder jwtDecoder() {
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withIssuerLocation(issuer).build();
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter
.withDefaults(Collections.singletonMap("sub", this::lookupUserIdBySub));
jwtDecoder.setClaimSetConverter(converter);
return jwtDecoder;
}
@Bean
fun jwtDecoder(): JwtDecoder {
val jwtDecoder = NimbusJwtDecoder.withIssuerLocation(issuer).build()
val converter = MappedJwtClaimSetConverter
.withDefaults(mapOf("sub" to this::lookupUserIdBySub))
jwtDecoder.setClaimSetConverter(converter)
return jwtDecoder
}
这将保留所有默认设置,但会覆盖 sub
的默认声明转换器。
添加声明
MappedJwtClaimSetConverter
也可以用来添加自定义声明,例如,以适应现有系统:
- Java
- Kotlin
MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("custom", custom -> "value"));
MappedJwtClaimSetConverter.withDefaults(mapOf("custom" to Converter<Any, String> { "value" }))
移除声明
移除一个声明也很简单,使用相同的 API:
- Java
- Kotlin
MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("legacyclaim", legacy -> null));
MappedJwtClaimSetConverter.withDefaults(mapOf("legacyclaim" to Converter<Any, Any> { null }))
重命名声明
在更复杂的情况下,比如同时查询多个声明或重命名声明时,Resource Server 接受任何实现 Converter<Map<String, Object>, Map<String,Object>>
的类:
- Java
- Kotlin
public class UsernameSubClaimAdapter implements Converter<Map<String, Object>, Map<String, Object>> {
private final MappedJwtClaimSetConverter delegate =
MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
public Map<String, Object> convert(Map<String, Object> claims) {
Map<String, Object> convertedClaims = this.delegate.convert(claims);
String username = (String) convertedClaims.get("user_name");
convertedClaims.put("sub", username);
return convertedClaims;
}
}
class UsernameSubClaimAdapter : Converter<Map<String, Any?>, Map<String, Any?>> {
private val delegate = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap())
override fun convert(claims: Map<String, Any?>): Map<String, Any?> {
val convertedClaims = delegate.convert(claims)
val username = convertedClaims["user_name"] as String
convertedClaims["sub"] = username
return convertedClaims
}
}
然后,可以像平常一样提供实例:
- Java
- Kotlin
@Bean
JwtDecoder jwtDecoder() {
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withIssuerLocation(issuer).build();
jwtDecoder.setClaimSetConverter(new UsernameSubClaimAdapter());
return jwtDecoder;
}
@Bean
fun jwtDecoder(): JwtDecoder {
val jwtDecoder: NimbusJwtDecoder = NimbusJwtDecoder.withIssuerLocation(issuer).build()
jwtDecoder.setClaimSetConverter(UsernameSubClaimAdapter())
return jwtDecoder
}
配置超时
默认情况下,资源服务器使用 30 秒的连接和套接字超时时间来与授权服务器协调。
这在某些场景下可能太短了。此外,它没有考虑到更复杂的模式,比如退避和发现。
要调整Resource Server连接到授权服务器的方式,NimbusJwtDecoder
接受一个RestOperations
的实例:
- Java
- Kotlin
@Bean
public JwtDecoder jwtDecoder(RestTemplateBuilder builder) {
RestOperations rest = builder
.setConnectTimeout(Duration.ofSeconds(60))
.setReadTimeout(Duration.ofSeconds(60))
.build();
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withIssuerLocation(issuer).restOperations(rest).build();
return jwtDecoder;
}
@Bean
fun jwtDecoder(builder: RestTemplateBuilder): JwtDecoder {
val rest: RestOperations = builder
.setConnectTimeout(Duration.ofSeconds(60))
.setReadTimeout(Duration.ofSeconds(60))
.build()
return NimbusJwtDecoder.withIssuerLocation(issuer).restOperations(rest).build()
}
默认情况下,资源服务器会在内存中缓存授权服务器的 JWK 集合 5 分钟,你可能需要调整这个时间。此外,它不考虑更复杂的缓存模式,如淘汰机制或使用共享缓存。
要调整 Resource Server 缓存 JWK 集合的方式,NimbusJwtDecoder
接受一个 Cache
实例:
- Java
- Kotlin
@Bean
public JwtDecoder jwtDecoder(CacheManager cacheManager) {
return NimbusJwtDecoder.withIssuerLocation(issuer)
.cache(cacheManager.getCache("jwks"))
.build();
}
@Bean
fun jwtDecoder(cacheManager: CacheManager): JwtDecoder {
return NimbusJwtDecoder.withIssuerLocation(issuer)
.cache(cacheManager.getCache("jwks"))
.build()
}
当给定一个 Cache
时,资源服务器将使用 JWK 集合 URI 作为键,并将 JWK 集合 JSON 作为值。
Spring 并不是一个缓存提供者,因此你需要确保包含适当的依赖项,比如 spring-boot-starter-cache
和你最喜欢的缓存提供者。
无论是套接字还是缓存超时,您可能希望直接使用 Nimbus。为此,请记住 NimbusJwtDecoder
附带了一个构造函数,该构造函数接受 Nimbus 的 JWTProcessor
。