Spring Boot 3.2+需弃用spring-security-oauth2-autoconfigure,改用starter-security、starter-oauth2-client和starter-oauth2-resource-server;配置GitHub OAuth2客户端时须严格匹配redirect-uri;SecurityFilterChain中必须显式调用.oauth2Login();资源服务器校验JWT需配置issuer-uri与jwk-set-uri并确保端点可访问。

在SpringBoot 5.2中启用安全认证并集成OAuth2,需避开已废弃的spring-security-oauth2-autoconfigure,改用Spring Security 6.2+原生支持的OAuth2 Client与Authorization Server模块,否则启动报错或令牌校验失败。
替换过时依赖并引入新版安全组件
打开pom.xml,删除所有含spring-security-oauth2-autoconfigure或spring-boot-starter-oauth2-client(2.x旧版)的依赖项。
添加以下三项核心依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
【必须使用Spring Boot 3.2+配套的starter】若仍用Spring Boot 5.2(实际应为3.2.x——Spring Boot无5.2版本),请确认项目真实版本号;否则依赖无法解析,编译直接失败。
配置OAuth2客户端(以GitHub为例)
在application.yml中写入:
spring:
security:
oauth2:
client:
registration:
github:
client-id: your_github_client_id
client-secret: your_github_client_secret
scope: read:user,user:email
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: login
注意:GitHub要求redirect-uri必须与开发者后台注册的完全一致,且必须是http://localhost:8080/login/oauth2/code/github(开发环境)或对应生产域名路径,否则回调404或invalid_redirect_uri。
声明式安全配置(SecurityFilterChain)
创建SecurityConfig.java,定义安全链:
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authz -> authz
.requestMatchers("/","/login","/error").permitAll()
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/api/admin/**").hasAuthority("SCOPE_admin")
.anyRequest().authenticated())
.oauth2Login(oauth2 -> oauth2
.loginPage("/login")
.defaultSuccessUrl("/home", true))
.logout(logout -> logout
.logoutSuccessUrl("/login?logout"));
return http.build();
}
}
这一步必须显式调用.oauth2Login(),否则OAuth2登录入口不生效;hasAuthority("SCOPE_admin")对应GitHub OAuth返回的scope字段,不是角色名,不可写成hasRole("ADMIN")。
资源服务器JWT令牌校验(对接自建授权服务)
若后端API需验证来自自建授权服务器的JWT,而非GitHub等第三方:
第一步:在application.yml中补充:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://auth.example.com
jwk-set-uri: https://auth.example.com/oauth2/jwks
第二步:确保授权服务器暴露/.well-known/oauth-authorization-server和/oauth2/jwks端点,且HTTPS可用;否则Spring会抛InvalidTokenException并拒绝所有请求。
第三步:在控制器方法上添加注解控制访问权限:
@GetMapping("/api/data")
@PreAuthorize("authentication.principal.attributes['scope'].contains('read')")
public Map<String, Object> getData() { ... }

















