摘要
关于早些时候的Spring Security版本中,可以使用spring-security-oauth2
和spring-security-oauth2-autoconfigure
依赖来实现OAuth 2.0。然而,随着新版本的发布,Spring Security 5 引入了新的OAuth2客户端和资源服务器支持,而且Spring Security团队已经推出了一个新的项目Spring Authorization Server来替代spring-security-oauth2
作为授权服务器。
本文为复现通过spring-boot-starter-oauth2-resource-server
和spring-security-oauth2-autoconfigure
实现OAuth 2.0及介绍迁移到更现代的解决方案。通常将一个项目配置成资源服务器以保护资源,另一个项目配置成授权服务器以发放令牌。
以下是如何实现的示例:
资源服务器配置
首先,确保添加了资源服务器的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
然后,在application.yml
或application.properties
中配置JWT令牌支持:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://your-auth-server.com # 授权服务器的issuer URI
资源服务器的安全配置类可能如下所示:
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.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authz -> authz
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt());
}
}
授权服务器配置
对于授权服务器,添加以下依赖以使用spring-security-oauth2-autoconfigure
:
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
在application.yml
中添加授权服务器配置:
security:
oauth2:
client:
client-id: your-client-id
client-secret: your-client-secret
authorized-grant-types: authorization_code,refresh_token,password,client_credentials
scope: read,write
authorization:
check-token-access: isAuthenticated()
然后,配置授权服务器和安全配置:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
// 在这里配置授权服务器的端点、客户端详情、令牌存储等
}
总结
由于spring-security-oauth2-autoconfigure
已经过时,并且它的功能在Spring Security 5中已经由原生支持取代,因此强烈建议迁移到Spring Security 5的OAuth2功能,或考虑使用Spring Authorization Server。
如果仍需要继续使用spring-security-oauth2-autoconfigure
(可能是因为遗留系统兼容性等原因),那么可能需要查看更详细的文档和案例,因为这涉及到较旧版本的配置方法,包括在AuthorizationServerConfigurerAdapter
实现中定义授权端点、令牌服务和安全约束。
请注意,Spring Boot 2.3.x版本的维护截至2021年已经结束,Spring Security 5不再包含OAuth 2.0 Authorization Server的支持,使用上述旧版本的方法应当谨慎,并计划迁移到更现代的解决方案。
基于security-oauth2-autoconfigure实现的OAuth2迁移到更现代的解决方案,Spring Security 5中使用OAuth2配合JWT实现安全认证-CSDN博客