Spring Security 与 OAuth 2.0 登录实现指南

embedded/2024/10/18 23:24:19/

文章目录

    • 一、项目概述
    • 二、环境准备
    • 三、创建GitHub OAuth应用
    • 四、项目依赖配置
    • 五、配置OAuth 2.0
    • 六、创建控制器
    • 七、创建视图
    • 八、运行应用
    • 九、用户界面展示
    • 十、总结

在现代的Web应用中,安全性是一个不可忽视的因素。OAuth 2.0作为一种流行的授权框架,提供了一种便捷的方式让用户通过社交平台(如GitHub)登录你的应用。本文将详细介绍如何使用Spring Security实现OAuth 2.0登录,并在页面上展示用户信息。

一、项目概述

本项目旨在实现一个简单的Web应用,允许用户通过GitHub进行登录。我们将使用Spring Boot和Spring Security进行快速开发。

二、环境准备

确保你已经安装了以下环境:

  • JDK 8或更高版本
  • Maven或Gradle
  • IDE(如IntelliJ IDEA或Eclipse)

三、创建GitHub OAuth应用

在开始编码之前,你需要在GitHub上创建一个OAuth应用。以下是创建过程的步骤:

  1. 登录GitHub:访问GitHub官网并登录你的账号。

  2. 进入设置:点击右上角的个人头像,选择“Settings”。

    进入设置

  3. 找到OAuth应用:在左侧菜单中,点击“Developer settings”,然后选择“OAuth Apps”。

    找到OAuth应用

    image-20241012150219059

  4. 注册新应用:点击“New OAuth App”按钮。

    注册新应用

  5. 填写应用信息:填写应用名称、主页 URL 和回调 URL(通常是 http://localhost:8080/login/oauth2/code/github),然后点击“Register application”。

    填写应用信息

  6. 获取Client ID和Client Secret:注册完成后,你会看到Client ID和Client Secret,保存这两个值。

    获取Client ID和Client Secretimage-20241012151907683image-20241012152020757

四、项目依赖配置

在你的pom.xml中添加以下依赖(如果你使用的是Maven):

image-20241012152612818

<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-thymeleaf</artifactId>
</dependency>

五、配置OAuth 2.0

application.yml中配置GitHub的OAuth 2.0客户端信息,填入你在上面步骤中获取的client-idclient-secret

spring:security:oauth2:client:registration:github:client-id: 填入你的数据client-secret: 填入你的数据

六、创建控制器

接下来,我们需要创建一个控制器来处理登录后的请求。以下是IndexController的代码:

java">package com.takumilove.oauth2logindemo.controller;import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
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;/*** @author RaoPengFei* @create 2024/10/12*/
@Controller
public class IndexController {@GetMapping("/")public String index(Model model, @RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,@AuthenticationPrincipal OAuth2User oauth2User) {model.addAttribute("userName", oauth2User.getName());model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());model.addAttribute("userAttributes", oauth2User.getAttributes());return "index";}
}

七、创建视图

使用Thymeleaf创建登录后的视图,以下是index.html的代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head><title>Spring Security - OAuth 2.0 Login</title><meta charset="utf-8" />
</head>
<body>
<div style="float: right" th:fragment="logout" sec:authorize="isAuthenticated()"><div style="float:left"><span style="font-weight:bold">User: </span><span sec:authentication="name"></span></div><div style="float:none">&nbsp;</div><div style="float:right"><form action="#" th:action="@{/logout}" method="post"><input type="submit" value="Logout" /></form></div>
</div>
<h1>OAuth 2.0 Login with Spring Security</h1>
<div>You are successfully logged in <span style="font-weight:bold" th:text="${userName}"></span>via the OAuth 2.0 Client <span style="font-weight:bold" th:text="${clientName}"></span>
</div>
<div>&nbsp;</div>
<div><span style="font-weight:bold">User Attributes:</span><ul><li th:each="userAttribute : ${userAttributes}"><span style="font-weight:bold" th:text="${userAttribute.key}"></span>: <span th:text="${userAttribute.value}"></span></li></ul>
</div>
</body>
</html>

八、运行应用

确保所有配置无误后,运行你的Spring Boot应用。访问http://localhost:8080,你将看到一个通过GitHub登录的选项。

九、用户界面展示

在用户成功登录后,界面将显示用户信息,如下图所示:

登录成功界面

十、总结

本文详细介绍了如何使用Spring Security实现OAuth 2.0登录,并展示了用户信息。希望通过这些步骤,你能够顺利地实现GitHub登录功能,提升你的应用安全性和用户体验。


http://www.ppmy.cn/embedded/126856.html

相关文章

【Spring】获取 Cookie和Session

回顾 Cookie HTTP 协议自身是属于“无状态”协议 无状态&#xff1a;默认情况下&#xff0c;HTTP 协议的客户端和服务器之间的这次通信和下次通信之间没有直接的联系 但是在实际开发中&#xff0c;我们很多时候是需要知道请求之间的关联关系的 例如登录网站成功后&#xff…

ClickHouse 数据保护指南:从备份到迁移的全流程攻略

一、背景 运行3年的clickhouse需要迁移机房&#xff0c;迁移单库单表的140亿条的数据。采用clickhouse-backup 的方式进行备份迁移&#xff0c;打包备份&#xff0c;再加上数据拷贝&#xff0c;数据恢复 一共花费30分钟。数据在一定量级&#xff0c;避免使用SQL 导入导出的方式…

FunASR离线文件转写服务开发指南-debian-10.13

FunASR离线文件转写服务开发指南-debian-10.13 服务器环境 debian10.13 64位 第一步 配置静态网卡 auto eth0 iface eth0 inet static address 192.168.1.100 netmask 255.255.255.0 gateway 192.168.1.1 dns-nameservers 8.8.8.8 8.8.4.4/etc/init.d/networking restart第…

数据结构-5.7.二叉树的层次遍历

一.演示&#xff1a; 1.初始化队列&#xff1a; 2.根结点入队&#xff1a; 3.判断队列是否为空&#xff0c;此时有根结点&#xff0c;说明不为空&#xff0c;则队头结点即根结点出队并访问&#xff0c;再先进它的左结点&#xff0c;最后进它的右结点&#xff1a; 4.之后对进来…

达梦数据守护主备实时同步集群搭建

达梦数据守护主备实时同步集群搭建 环境准备达梦数据库软件安装数据守护集群搭建:实例初始化数据守护集群搭建:备份恢复数据守护集群搭建:主库配置数据守护集群搭建:备库配置数据守护集群搭建:守护进程数据守护集群搭建:监视器数据守护集群搭建:主备切换环境准备 数据库…

UE5 C++ 通过绑定编辑器事件实现控制柄顶点编辑

开发中经常会遇到编辑器环境中制作工具拖拽控制柄编辑内容的需求&#xff0c;此时可以通过Editor事件拿到对应回调&#xff0c;进行相应更新&#xff1a; 1.创建Mesh编辑Actor类 创建一个Mesh编辑Actor类&#xff0c;提供Mesh顶点编辑的相关逻辑。 .h: #pragma once#inclu…

【最新华为OD机试E卷-支持在线评测】跳房子I(100分)多语言题解-(Python/C/JavaScript/Java/Cpp)

🍭 大家好这里是春秋招笔试突围 ,一枚热爱算法的程序员 💻 ACM金牌🏅️团队 | 大厂实习经历 | 多年算法竞赛经历 ✨ 本系列打算持续跟新华为OD-E/D卷的多语言AC题解 🧩 大部分包含 Python / C / Javascript / Java / Cpp 多语言代码 👏 感谢大家的订阅➕ 和 喜欢�…

Unity 判断手柄是否接入和断开

Input.GetJoystickNames()&#xff0c;会返回手柄名字列表&#xff0c;遍历判断即可。 为什么要遍历判断呢&#xff0c;这里有一个&#xff0c;如果接入了两个手柄&#xff0c;拔掉了一个&#xff0c;这个列表返回长度还是2&#xff0c;需要判断手柄名字是不是空&#xff0c;才…