当前位置: 首页 > news >正文

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
http://www.lryc.cn/news/586000.html

相关文章:

  • 力扣-19. 删除链表的倒数第N个节点
  • 什么是 Bootloader?怎么把它移植到 STM32 上?
  • 【6.1.3 漫画分布式锁】
  • 线程属性设置全攻略
  • 14. 请谈一下浏览器的强缓存和协商缓存
  • 9.2 埃尔米特矩阵和酉矩阵
  • Pandas 模块之数据的读取
  • arcgis投影后数据显示问题记录
  • 非程序员如何用 AI 提升日常工作效率:以产品经理为例的落地实践指南
  • error while loading shared libraries
  • 小架构step系列12:单元测试
  • [爬虫实战] 多进程/多线程/协程-异步爬取豆瓣Top250
  • Pytest 跳过测试技巧:灵活控制哪些测试该跑、哪些该跳过
  • linux系统mysql性能优化
  • H2在springboot的单元测试中的应用
  • 多 Agent 强化学习实践指南(一):CTDE PPO 在合作捕食者-猎物游戏中的应用详解
  • 引入了模块但没有使用”,会不会被打包进去
  • 【C++小白逆袭】内存管理从崩溃到精通的秘籍
  • c++反射实现
  • 张量数值计算
  • 跨系统开发代码换行符如何解决
  • 每日一SQL 【销售分析 III】
  • 试用了10款翻译软件后,我只推荐这一款!完全免费还超好用
  • 大模型KV缓存量化误差补偿机制:提升推理效率的关键技术
  • Qt6中出现 OpenCV(4.10.0) Error: Assertion failed
  • 第10讲——一元函数积分学的几何应用
  • 创建 UIKit 项目教程
  • 在 Java 中,计算两个 Integer 类型表示的合格数量与总数量的合格率,并保留四位小数,推荐使用 BigDecimal 来确保精度
  • springboot+swagger2文档从swagger-bootstrap-ui更换为knife4j及文档接口参数不显示问题
  • 股票的k线