
本文档旨在指导开发者如何使用 Spring Security 构建自定义 OAuth2 授权服务器,重点在于实现 PRIVATE_KEY_JWT 身份验证方法。通过配置 RSA 密钥、JWT 编码器和解码器,以及自定义 JWT 转换器,可以创建一个安全且灵活的授权服务器,从而为资源服务器提供有效的访问令牌。
首先,需要在 application.yml 文件中配置 RSA 密钥的位置。这将允许应用程序加载用于签名和验证 JWT 的私钥和公钥。
rsa: privateKey: classpath:certs/private.pem publicKey: classpath:certs/public.pem
确保 certs/private.pem 和 certs/public.pem 文件存在于您的 classpath 中,并且包含有效的 PEM 格式的私钥和公钥。
接下来,创建一个配置类 RsaKeyProperties 来加载这些密钥。
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
@Configuration
@ConfigurationProperties(prefix = "rsa")
public class RsaKeyProperties {
private RSAPrivateKey privateKey;
private RSAPublicKey publicKey;
public RSAPrivateKey getPrivateKey() {
return privateKey;
}
public void setPrivateKey(RSAPrivateKey privateKey) {
this.privateKey = privateKey;
}
public RSAPublicKey getPublicKey() {
return publicKey;
}
public void setPublicKey(RSAPublicKey publicKey) {
this.publicKey = publicKey;
}
}现在,配置 WebSecurityConfig 类来启用 OAuth2 资源服务器,并配置 JWT 编码器和解码器。
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
protected SecurityFilterChain configure(
BasicAuthenticationFilter basicAuthFilter,
HttpSecurity http) throws Exception {
return http
// Disabling CSRF is safe for token-based API's
.csrf().disable()
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeRequests(auth -> {
auth.antMatchers(
"/api/authenticate/**",
"/api/tenants/**").permitAll();
auth.antMatchers("/api/**").authenticated();
// When an exception is thrown, ErrorMvcAutoConfiguration sets stuff up so that /error is called
// internally using an anonymous user. Without this line, the call to /error fails with a 403 error
// because anonymous users would not be able to view the page.
auth.antMatchers("/error").anonymous();
})
.build();
}
@Bean
public JwtDecoder jwtDecoder(RsaKeyProperties rsaKeyProperties) {
return NimbusJwtDecoder.withPublicKey(rsaKeyProperties.getPublicKey()).build();
}
@Bean
public JwtEncoder jwtEncoder(RsaKeyProperties rsaKeyProperties) {
JWK jwk = new RSAKey.Builder(rsaKeyProperties.getPublicKey())
.privateKey(rsaKeyProperties.getPrivateKey())
.build();
JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));
return new NimbusJwtEncoder(jwks);
}
}这段代码配置了以下内容:
默认情况下,Spring Security 会将 "SCOPE_" 前缀添加到 JWT 中的所有权限声明中。如果您的身份验证服务器不使用此约定,则需要创建一个自定义的 JwtAuthenticationConverter 来删除此前缀。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
@Configuration
public class JwtConverterConfig {
/**
* For some reason the JwtGrantedAuthoritiesConverter defaults to adding the prefix "SCOPE_" to all
* the claims in the token, so we need to provide a JwtGrantedAuthoritiesConverter that doesn't do
* that and just passes them through.
*/
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthorityPrefix("");
JwtAuthenticationConverter authConverter = new JwtAuthenticationConverter();
authConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return authConverter;
}
}这段代码创建了一个 JwtAuthenticationConverter bean,它使用一个 JwtGrantedAuthoritiesConverter,该转换器将权限前缀设置为空字符串。这将确保权限声明不会被修改。
通过按照本文档中的步骤操作,您可以创建一个自定义的 OAuth2 授权服务器,该服务器使用 Spring Security 和 PRIVATE_KEY_JWT 身份验证方法。这将为您提供一个安全且灵活的解决方案,用于保护您的资源服务器。记住,安全性是一个持续的过程,因此请务必定期审查和更新您的配置,以应对新的威胁。
以上就是使用 Spring Security 实现自定义 OAuth2 授权的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号