Spring Boot 3.4.3 和 Spring Security 6.4.2 结合 OAuth2 实现 GitHub 授权登录

在现代 Web 应用中,第三方授权登录(如 GitHub、Google 等)已成为提升用户体验的重要功能。OAuth2 作为一种广泛使用的授权协议,能够安全地实现用户身份验证和资源访问。Spring Boot 3.4.3 结合 Spring Security 6.4.2,提供了对 OAuth2 的原生支持,使得集成第三方登录变得简单高效。本文将详细介绍如何在 Spring Boot 3.4.3 中使用 Spring Security 和 OAuth2 实现 GitHub 授权登录,并附上完整代码示例,助你在2025年的项目中快速实现社交登录功能。


1. OAuth2 和 GitHub 授权简介
1.1 什么是 OAuth2?

OAuth2 是一种授权框架,允许第三方应用在用户许可下访问其资源,而无需直接共享用户凭证。它通过 Access Token 实现安全授权,广泛用于社交登录场景。

1.2 GitHub 授权登录

GitHub 支持 OAuth2 协议,开发者可以通过注册应用获取 Client ID 和 Client Secret,使用户能够通过 GitHub 账户登录你的应用。

1.3 本文目标
  • 配置 Spring Security 支持 OAuth2。
  • 实现 GitHub 授权登录。
  • 获取用户信息并展示。

2. 项目实战

以下是基于 Spring Boot 3.4.3 和 Spring Security 6.4.2 实现 GitHub 授权登录的完整步骤。

2.1 添加 Maven 依赖

pom.xml 中添加必要的依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.4.3</version>
    </parent>
    <groupId>cn.itbeien</groupId>
    <artifactId>springboot-oauth2-github</artifactId>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <!-- Spring Boot Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Spring Security 和 OAuth2 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <!-- Thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>
</project>

说明:

  • spring-boot-starter-oauth2-client:提供 OAuth2 客户端支持。
  • spring-boot-starter-thymeleaf:用于渲染页面。
2.2 注册 GitHub OAuth 应用
  1. 登录 GitHub,进入 Settings > Developer settings > OAuth Apps
  2. 点击 New OAuth App,填写:
    • Application name:应用名称(如 “SpringBoot OAuth Demo”)。
    • Homepage URLhttp://localhost:8080
    • Authorization callback URLhttp://localhost:8080/login/oauth2/code/github
  3. 提交后获取 Client IDClient Secret
2.3 配置 OAuth2

application.yml 中配置 GitHub OAuth2 参数:

spring:
  security:
    oauth2:
      client:
        registration:
          github:
            client-id: your-client-id
            client-secret: your-client-secret
            scope: user # 请求用户信息权限
        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
  thymeleaf:
    cache: false # 开发时禁用缓存

说明:

  • client-idclient-secret:从 GitHub 获取。
  • scope:指定请求的权限范围。
2.4 配置 Spring Security

创建一个 Security 配置类:

package cn.joyous.config;

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 {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/", "/login").permitAll() // 公开首页和登录页
                        .anyRequest().authenticated() // 其他请求需认证
                )
                .oauth2Login(oauth2 -> oauth2
                        .loginPage("/login") // 自定义登录页
                        .defaultSuccessUrl("/home", true) // 登录成功跳转
                )
                .logout(logout -> logout
                        .logoutSuccessUrl("/").permitAll()
                );
        return http.build();
    }
}
2.5 创建控制器

处理登录和用户信息展示:

package cn.joyous.controller;

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 HomeController {

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/home")
    public String home(@AuthenticationPrincipal OAuth2User principal, Model model) {
        model.addAttribute("username", principal.getAttribute("login"));
        model.addAttribute("name", principal.getAttribute("name"));
        return "home";
    }
}
2.6 创建 Thymeleaf 页面
首页 (index.html)
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <h1>欢迎使用 OAuth2 登录</h1>
    <a href="/oauth2/authorization/github">使用 GitHub 登录</a>
</body>
</html>
登录页 (login.html)
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
    <h1>登录</h1>
    <a href="/oauth2/authorization/github">使用 GitHub 登录</a>
</body>
</html>
首页 (home.html)
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>欢迎</title>
</head>
<body>
    <h1>欢迎, <span th:text="${username}"></span>!</h1>
    <p>姓名: <span th:text="${name}"></span></p>
    <a href="/logout">退出登录</a>
</body>
</html>

将这些文件放入 src/main/resources/templates 目录。

2.7 启动与测试
  1. 启动 Spring Boot 应用。
  2. 访问 http://localhost:8080,点击“使用 GitHub 登录”。
  3. 跳转到 GitHub 授权页面,同意后返回 /home,显示用户信息。

3. 进阶功能(可选)
  1. 自定义用户信息
    处理 GitHub 返回的数据:

    @Bean
    public OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {
        DefaultOAuth2UserService delegate = new DefaultOAuth2UserService();
        return (userRequest) -> {
            OAuth2User oauth2User = delegate.loadUser(userRequest);
            Map<String, Object> attributes = new HashMap<>(oauth2User.getAttributes());
            attributes.put("customField", "customValue");
            return new DefaultOAuth2User(oauth2User.getAuthorities(), attributes, "login");
        };
    }
    
  2. 添加 REST API
    提供用户信息接口:

    @RestController
    @RequestMapping("/api")
    public class ApiController {
        @GetMapping("/user")
        public Map<String, Object> getUser(@AuthenticationPrincipal OAuth2User principal) {
            return principal.getAttributes();
        }
    }
    
  3. 多提供商支持
    application.yml 中添加其他提供商(如 Google):

    spring:
      security:
        oauth2:
          client:
            registration:
              google:
                client-id: your-google-client-id
                client-secret: your-google-client-secret
    

4. 总结

Spring Boot 3.4.3 和 Spring Security 6.4.2 结合 OAuth2,为第三方授权登录提供了简单高效的实现方式。本文以 GitHub 登录为例,从配置到页面展示,覆盖了核心步骤。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专业WP网站开发-Joyous

创作不易,感谢支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值