Spring Boot 整合 OAuth2 详细教程(适用于 2025 年 Spring Boot 3.x)
前言
OAuth2 是一种授权协议,广泛用于第三方登录、单点登录(SSO)和微服务架构中的身份验证。Spring Security 提供了对 OAuth2 的完整支持,包括客户端、资源服务器和授权服务器。
本教程将从零开始,手把手教你如何在 Spring Boot 3.x + Java 17+ 环境中整合 OAuth2,使用 GitHub 登录作为示例,并可扩展到 Google、Facebook 等平台。
一、开发环境准备
基础依赖
- Java 17 或以上
- Spring Boot 3.3.x(当前主流版本)
- Maven / Gradle 构建工具
- IDE:IntelliJ IDEA / VS Code / Eclipse
二、创建 Spring Boot 项目
你可以通过 Spring Initializr 创建一个基础项目:
- Project: Maven
- Language: Java
- Spring Boot Version: 3.3.x
- Dependencies:
- Spring Web
- Spring Security
- Spring Security OAuth2 Client
或者手动添加以下依赖到 pom.xml
文件中:
<dependencies><!-- Spring Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring Security --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><!-- OAuth2 Client --><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-oauth2-client</artifactId></dependency><!-- Thymeleaf (前端页面) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
</dependencies>
三、配置 OAuth2 客户端(以 GitHub 为例)
1. 获取 GitHub OAuth2 应用信息
前往 GitHub 开发者设置页面:
https://github.com/settings/developers
点击 New OAuth App 创建一个新的应用:
- Application name: 可自定义
- Homepage URL: http://localhost:8080
- Authorization callback URL: http://localhost:8080/login/oauth2/code/github
提交后你会获得两个关键参数:
Client ID
Client Secret
2. 配置 application.yml
spring:security:oauth2:client:registration:github:client-id: your-github-client-idclient-secret: your-github-client-secretscope: user:emailredirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"client-name: GitHubprovider: githubprovider:github:authorization-uri: https://github.com/login/oauth/authorizetoken-uri: https://github.com/login/oauth/access_tokenuser-info-uri: https://api.github.com/useruser-name-attribute: login
四、安全配置类(启用 OAuth2 登录)
创建一个配置类 SecurityConfig.java
:
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.web.SecurityFilterChain;@Configuration
@EnableWebSecurity
public class SecurityConfig {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(auth -> auth.requestMatchers("/", "/login**", "/error**").permitAll().anyRequest().authenticated()).oauth2Login(oauth2 -> oauth2.defaultSuccessUrl("/home"));return http.build();}
}
关键配置说明:
方法 | 作用 |
---|---|
.authorizeHttpRequests() | 控制访问权限 |
.requestMatchers(...) | 允许未认证用户访问的路径 |
.oauth2Login() | 启用 OAuth2 登录流程 |
.defaultSuccessUrl("/home") | 登录成功跳转路径 |
五、控制器与页面展示
1. 控制器类 AuthController.java
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;@Controller
public class AuthController {@GetMapping("/")public String index() {return "index";}@GetMapping("/home")public String home(Model model, @AuthenticationPrincipal OAuth2User principal) {model.addAttribute("name", principal.getAttribute("login"));model.addAttribute("email", principal.getAttribute("email"));return "home";}
}
2. 页面模板(Thymeleaf)
src/main/resources/templates/index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"><head><title>Login with GitHub</title></head><body><h1>Welcome to OAuth2 Demo</h1><a th:href="@{/oauth2/authorization/github}">Login with GitHub</a></body>
</html>
src/main/resources/templates/home.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"><head><title>Home Page</title></head><body><h1>Hello, <span th:text="${name}"></span>!</h1><p>Email: <span th:text="${email}"></span></p><a href="/logout">Logout</a></body>
</html>
六、运行测试
启动 Spring Boot 应用:
./mvnw spring-boot:run
打开浏览器访问:
http://localhost:8080/
点击“Login with GitHub”,跳转至 GitHub 授权页面。授权后返回 /home
页面,显示 GitHub 用户名和邮箱。
七、多平台支持(Google、Facebook)
只需添加新的注册项即可支持其他 OAuth2 提供商:
示例:Google 登录
spring:security:oauth2:client:registration:google:client-id: your-google-client-idclient-secret: your-google-client-secretscope: email,profileredirect-uri: "{baseUrl}/login/oauth2/code/google"client-name: Googleprovider:google:authorization-uri: https://accounts.google.com/o/oauth2/v2/authtoken-uri: https://www.googleapis.com/oauth2/v4/tokenuser-info-uri: https://www.googleapis.com/oauth2/v3/userinfouser-name-attribute: sub
然后在页面上增加链接:
<a th:href="@{/oauth2/authorization/google}">Login with Google</a>
八、搭建自己的 OAuth2 授权服务器(进阶)
如果你想构建自己的 OAuth2 授权服务器(如统一认证中心),可以使用 Spring Authorization Server(替代旧版 Spring Security OAuth)。
添加依赖:
<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-oauth2-resource-server</artifactId>
</dependency>
<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-config</artifactId>
</dependency>
示例配置类:
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.web.SecurityFilterChain;@Configuration
@EnableWebSecurity
public class AuthServerSecurityConfig {@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()).formLogin();return http.build();}
}
你还需要配置客户端、令牌生成等高级功能,这部分内容建议参考官方文档:
🔗 Spring Authorization Server 文档
九、常见问题与解决方案
问题 | 解决方案 |
---|---|
Callback URL 不匹配 | 检查 GitHub 设置中的回调地址是否为 http://localhost:8080/login/oauth2/code/github |
Scope 权限不足 | 修改 scope 字段,如 user:email |
登录失败无提示 | 添加日志输出或实现 OAuth2AuthenticationFailureHandler |
多个 OAuth2 提供商冲突 | 使用不同的 registrationId 区分 |
用户信息为空 | 检查 user-name-attribute 是否正确,GitHub 为 login ,Google 为 sub |
十、总结
内容 | 技术 |
---|---|
OAuth2 客户端 | Spring Security OAuth2 Client |
第三方登录 | GitHub / Google |
用户信息处理 | @AuthenticationPrincipal OAuth2User |
前端展示 | Thymeleaf |
自定义授权服务器 | Spring Authorization Server |
十一、参考资料
- Spring Security OAuth2 Login Docs
- Spring Authorization Server GitHub
- GitHub OAuth Apps
- Google OAuth2 Guide