spring security 5.7+ 已移除旧oauth2支持,新项目应使用spring-authorization-server和spring-security-oauth2-resource-server;resource server需正确配置issuer-uri与jws算法;client registration须与第三方平台严格一致;自建授权服务器需实现registeredclientrepository等关键组件。

Spring Security OAuth2 配置前先确认废弃状态
Spring Security 5.7+ 已彻底移除 spring-security-oauth2(即旧的 @EnableAuthorizationServer),官方明确标记为“deprecated since 5.2, removed in 5.7”。现在用的是 spring-security-oauth2-resource-server 和 spring-authorization-server(独立项目)。如果你在抄老教程配 AuthorizationServerConfigurerAdapter,代码根本编译不过。
常见错误现象:ClassNotFoundException: org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter
- 新项目直接用
spring-authorization-server(0.4.0+ 支持 Spring Boot 3 / Jakarta EE 9+) - 老项目升级:若还在用 Spring Boot 2.7.x,可暂留
spring-security-oauth2-autoconfigure,但仅限 Resource Server 场景 - 别再往
WebSecurityConfigurerAdapter里塞 OAuth2 配置逻辑——它本身也在 Spring Security 6 中被移除
Resource Server 怎么验证 JWT 访问令牌
这是最常卡住的地方:服务端能接收请求,但始终返回 401 Unauthorized,日志里却没报错。问题往往出在 JWT 签名密钥或 Issuer 验证上。
关键点是 jwtDecoder() 的配置必须和授权服务器签发的 token 完全匹配:
立即学习“Java免费学习笔记(深入)”;
-
issuer-uri必须指向授权服务器的/.well-known/openid-configuration(如https://auth.example.com),不能只写域名 - 若用对称密钥(HMAC),需手动配置
JwtDecoders.fromIssuerLocation()+NimbusJwtDecoderJwkSetUri不适用,得用JwtDecoders.fromSecretKey() - Spring Boot 3 默认启用
spring.security.oauth2.resourceserver.jwt.jws-algorithm检查,若授权服务器用RS256而你配成HS256,会静默失败
示例(application.yml):
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://auth.example.com
jws-algorithm: RS256
Client Registration 怎么填才不跳 302 到登录页
用 spring-security-oauth2-client 做登录时,点击“Login with Google”后跳回首页、没弹授权页,或重定向 URL 报错 redirect_uri_mismatch,基本是 client registration 配置和 OAuth2 提供商后台不一致。
-
client-id和client-secret必须和你在 Google Cloud Console / Auth0 / Keycloak 后台创建的 OAuth App 完全一致(注意环境区分:localhost vs 生产域名) -
redirect-uri默认是{baseUrl}/login/oauth2/code/{registrationId},但必须在提供商后台显式注册该完整 URL(例如http://localhost:8080/login/oauth2/code/google) - 如果用了反向代理(Nginx),
baseUrl可能被识别成http://localhost:8080,需加server.forward-headers-strategy=framework并配置X-Forwarded-*头
自建 Authorization Server 怎么避免踩 spring-authorization-server 的坑
这个库设计上更贴近 OAuth 2.1 规范,但默认行为和旧框架差异大:比如不自动提供 /oauth/authorize 页面,也不内置用户认证流程。
- 必须自己实现
RegisteredClientRepository,不能只靠内存 Map —— 否则重启后 client 丢失,token 刷新失败 -
OAuth2TokenGenerator默认用JwtEncodingContext生成 JWT,但若没配signingKey,启动时报No key configured for signing - 客户端模式(client_credentials)需要显式调用
OAuth2TokenCustomizer才能往 access token 里加 scope 或 claims,不像以前自动继承
最容易被忽略的一点:它不处理用户登录表单,/oauth2/authorize 请求进来后,会交还给 Spring Security 的普通认证流程(比如表单登录)。你得自己决定是接 Spring Security 的 UsernamePasswordAuthenticationFilter,还是重定向到前端登录页。










