36 lines
1.7 KiB
Java
36 lines
1.7 KiB
Java
package com.baiyue.auth.config;
|
|
|
|
import com.nimbusds.jose.jwk.JWKSet;
|
|
import com.nimbusds.jose.jwk.RSAKey;
|
|
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
|
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
|
import org.springframework.context.annotation.Bean;
|
|
import org.springframework.context.annotation.Configuration;
|
|
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
|
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
|
|
|
|
@Configuration(proxyBeanMethods = false)
|
|
@EnableConfigurationProperties(UnifiedJwtProperties.class)
|
|
public class UnifiedJwtConfiguration {
|
|
@Bean("jwtEncoder")
|
|
JwtEncoder jwtEncoder(UnifiedJwtProperties properties) {
|
|
try {
|
|
JWKSet set = JWKSet.parse(properties.rsaJwkSet());
|
|
RSAKey current = set.getKeyByKeyId(properties.currentKid()) instanceof RSAKey rsa ? rsa : null;
|
|
if (current == null || !current.isPrivate()) {
|
|
throw new IllegalStateException("统一 current-kid 必须指向包含私钥的 RSA 密钥");
|
|
}
|
|
if (set.getKeys().stream().anyMatch(jwk -> !(jwk instanceof RSAKey))) {
|
|
throw new IllegalStateException("统一 JWK Set 只能包含 RSA 密钥");
|
|
}
|
|
if (set.getKeys().stream().anyMatch(jwk -> !properties.currentKid().equals(jwk.getKeyID())
|
|
&& jwk instanceof RSAKey rsa && rsa.isPrivate())) {
|
|
throw new IllegalStateException("统一非当前密钥只能配置公钥");
|
|
}
|
|
return new NimbusJwtEncoder(new ImmutableJWKSet<>(set));
|
|
} catch (java.text.ParseException exception) {
|
|
throw new IllegalStateException("统一 RSA JWK Set 配置无效", exception);
|
|
}
|
|
}
|
|
}
|