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

项目练习:SpringSecurity+OAuth2接入gitee的第三方登陆(授权码模式)

文章目录

  • 一、知识准备
    • 1、OAuth2的角色
    • 2、使用场景
    • 3、四种授权模式
  • 二、案例实现
    • 1、gitee上注册应用
    • 2、直接通过手动发送http请求方式
    • 3、项目代码方式
    • 4、测试方法

一、知识准备

1、OAuth2的角色

1、资源所有者(Resource 0wner):即用户,资源的拥有人,想要通过客户应用访问资源服务器上的资源。
2、客户应用(client):通常是一个web或者无线应用,它需要访问用户的受保护资源。
3、资源服务器(Resource Server):存储受保护资源的服务器或定义了可以访问到资源的API,接收并验证客户端的访问令牌,以决定是否授权访问资源。
4、授权服务器(Authorization Server):负责验证资源所有者的身份并向客户端颁发放访问令牌

2、使用场景

使用第三方账号登陆当前系统

3、四种授权模式

1、授权码(最常用)
2、隐藏式
3、密码式
4、客户端凭证(机器对接机器)

四种模式的选择
在这里插入图片描述

二、案例实现

1、gitee上注册应用

点击设置
在这里插入图片描述
左侧下滑,选择第三方应用
在这里插入图片描述
创建应用
在这里插入图片描述
填写应用信息
http://localhost:8088/login/oauth2/code/gitee
在这里插入图片描述
创建成功后,我们可以得到ClientId和ClientSecret
在这里插入图片描述

2、直接通过手动发送http请求方式

大致分为两步
1、获取token

此次请求,gitee会通过配置的应用回调地址,返回一个code给我们
需要再浏览器中发起请求
https://gitee.com/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code

带上第一次返回的code及其他相关参数,这次请求会返回token给我们
需要再postman中发请求
https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}

2、通过token获取用户信息

带上第一步中获取的token作为参数
https://gitee.com/api/v5/user?access_token=672bdec6268716a4011e5f633979b444

3、项目代码方式

  • common模块
        <!-- spring security 安全认证 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <!-- oauth2 客户端 -->
        <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>

security.oauth2.client中自带的几个重要的原生类
OAuth2ClientProperties、CommonOAuth2Provider

  • admin模块的application.yml配置gitee信息
# Spring配置
spring:
  security:
    oauth2:
      client:
        registration:
          gitee:
            provider: gitee
            client-id: 填写你自己的clientId
            client-secret: 填写自己的ClientSecret
            # 重定向的url地址,这个地址为默认的,改成自己项目的IP和PORT即可。
            redirect-uri: http://localhost:8088/login/oauth2/code/gitee
            authorization-grant-type: "authorization_code"
            client-name: gitee
        #不配置这个会报 gitee找不到
        provider:
          gitee:
            authorization-uri: https://gitee.com/oauth/authorize
            token-uri: https://gitee.com/oauth/token
            user-info-uri: https://gitee.com/api/v5/user
            user-name-attribute: "name"
  • framework的SecurityConfig
http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated());
http.oauth2Client(Customizer.withDefaults());
  • admin模块
    新增controller
@Controller
public class OAuth2LoginController {
	@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";
	}
	
	@GetMapping("/test")
	public String test(){
		return "test";		//返回test.html页面
	}

}

新增test.html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试页</title>
</head>
<body>
<h1>这是一个测试页面!</h1>
</body>
</html>

新增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>

4、测试方法

浏览器访问:http://localhost:8088/login
在这里插入图片描述
成功拿到gitee的用户信息


http://www.kler.cn/a/534691.html

相关文章:

  • UG NX二次开发(Python)-API函数介绍与应用实例(三)-UFLayer类操作
  • 2025蓝桥杯JAVA编程题练习Day2
  • Python自动化测试selenium指定截图文件名方法
  • 排序算法--计数排序
  • AWS门店人流量数据分析项目的设计与实现
  • HTML5 教程之标签(3)
  • 二进制/源码编译安装httpd 2.4,提供系统服务管理脚本并测试
  • 简单说一下CAP理论和Base理论
  • 办理CE-notify-body资质流程详细讲解
  • 细说机器学习数学优化之梯度下降
  • Pytorch与大模型有什么关系
  • 当孤独遇上AI:“爱陪伴”如何治愈孤独缓解压力?
  • 如何用hooks实现redux?
  • Java面试题(11) 整理Java面试题及参考答案
  • hot100-day1
  • InDraw绘制的结构式,一键复制到Word里
  • aliyun 的 ip 设置方法
  • Tomcat 的几种部署方式
  • Unity UI Default Shader分析
  • CSS盒模型详解:从零开始理解margin、border、padding
  • vue3+ts 引入 json-editor-vue3
  • 什么是三层交换技术?与二层有什么区别?
  • 自定义线程池应用加源码分析
  • 2.5学习总结(补)
  • 运维作业四
  • 使用DeepSeek搭建个人专属知识库