Spring Security 6集成OAuth 2.0和JWT需引入授权服务器与资源服务器依赖,配置客户端详情、JWT解码器及授权规则,通过JwtClaimsSetCustomizer定制声明,使用BCrypt等安全密码编码,结合ClientRegistrationRepository实现第三方登录,利用SpEL或AccessDecisionVoter实现细粒度权限控制,支持刷新令牌机制,并通过黑名单、短有效期或服务端存储应对JWT吊销问题。

Spring Security 6 中集成 OAuth 2.0 和 JWT,核心在于构建一个安全的、可扩展的授权体系,让你的应用能够代表用户安全地访问受保护的资源。 这不仅提升了安全性,还简化了跨应用的用户认证和授权流程。
OAuth 2.0 + JWT 集成方案
依赖引入: 首先,确保你的
pom.xml
spring-boot-starter-oauth2-authorization-server
spring-boot-starter-oauth2-resource-server
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>配置授权服务器: 创建一个配置类来定义授权服务器的行为。 你需要配置客户端详情(client details),包括客户端 ID、密钥、授权类型(authorization grant types)、重定向 URI 和 scope。
@Configuration
@EnableWebSecurity
public class AuthorizationServerConfig {
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("your-client-id")
.clientSecret("{noop}your-client-secret") // 生产环境不要用 noop
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.redirectUri("http://127.0.0.1:8080/login/oauth2/code/your-client-id")
.scope(OidcScopes.OPENID)
.scope("read")
.build();
return new InMemoryRegisteredClientRepository(registeredClient);
}
@Bean
public ProviderSettings providerSettings() {
return ProviderSettings.builder().issuer("http://auth-server:9000").build();
}
// ... 其他配置,例如 JWKSource
}配置资源服务器: 资源服务器需要知道如何验证 JWT。 你需要配置 JWT 解码器(JWT Decoder)和授权规则。
@Configuration
@EnableWebSecurity
public class ResourceServerConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
)
.oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
}JWT 定制: 可以通过实现
JwtClaimsSetCustomizer
@Bean
public JwtClaimsSetCustomizer<OAuth2TokenClaimsContext> jwtClaimsSetCustomizer() {
return context -> {
// 添加自定义声明
context.getClaims().claim("custom-claim", "some-value");
};
}安全性考量: 永远不要在生产环境中使用
{noop}Spring Security 6 OAuth 2.0 授权码模式如何集成第三方登录?
集成第三方登录的关键在于配置
ClientRegistrationRepository
application.yml
application.properties
spring:
security:
oauth2:
client:
registration:
github:
client-id: your-github-client-id
client-secret: your-github-client-secret
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
scope: read:user
provider:
github:
authorization-uri: https://github.com/login/oauth/authorize
token-uri: https://github.com/login/oauth/access_token
user-info-uri: https://api.github.com/user
user-name-attribute: id然后,你可以使用
@EnableOAuth2Sso
Spring Security 6 OAuth 2.0 如何实现资源服务器的细粒度权限控制?
细粒度权限控制通常涉及到使用 Spring Security 的表达式语言(SpEL)或自定义的
AccessDecisionVoter
@PreAuthorize
@PostAuthorize
@GetMapping("/admin/users/{userId}")
@PreAuthorize("hasRole('ADMIN') and #userId == principal.id")
public User getUser(@PathVariable Long userId) {
// ...
}或者,你可以创建一个自定义的
AccessDecisionVoter
JWT 的刷新令牌(Refresh Token)机制在 Spring Security 6 中如何实现?
刷新令牌允许客户端在访问令牌过期后,无需用户重新授权即可获取新的访问令牌。 你需要在授权服务器中配置刷新令牌的支持,并确保客户端在获取访问令牌时也请求刷新令牌。
@Bean
public AuthorizationServerSettings authorizationServerSettings() {
return AuthorizationServerSettings.builder()
.authorizationEndpoint("/oauth2/authorize")
.tokenEndpoint("/oauth2/token")
.tokenRevocationEndpoint("/oauth2/revoke")
.jwkSetEndpoint("/oauth2/jwks")
.build();
}当访问令牌过期时,客户端可以使用刷新令牌向授权服务器请求新的访问令牌。 授权服务器会验证刷新令牌的有效性,并颁发新的访问令牌和刷新令牌。
如何处理 JWT 的吊销(Revocation)问题?
JWT 本身是自包含的,一旦颁发就无法直接撤销。 但是,你可以通过几种方法来处理 JWT 的吊销问题:
选择哪种方法取决于你的安全需求和性能考虑。 黑名单方法简单易用,但可能会影响性能。 缩短有效期可以减少风险,但会增加令牌刷新的频率。 令牌存储方法提供了最高的安全性,但会增加服务器端的存储和处理负担。
以上就是SpringSecurity6安全实战:OAuth2.0与JWT集成最佳实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号