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

Spring Boot OAuth 2.0整合详解

目录

一、Spring Boot 2.x 示例

1、初始化设置

2、设置重定向URI

3、配置 application.yml

4、启动应用程序

二、Spring Boot 2.x 属性映射

二、CommonOAuth2Provider

三、配置自定义提供者(Provider)属性

四、覆盖 Spring Boot 2.x 的自动配置

五、注册一个 ClientRegistrationRepository @Bean

六、注册一个 SecurityFilterChain @Bean

七、完全覆盖自动配置

八、不使用 Spring Boot 2.x 的 Java 配置


一、Spring Boot 2.x 示例

Spring Boot 2.x为OAuth 2.0登录带来了全面的自动配置功能。

本节展示了如何通过使用Google作为认证提供者来配置 OAuth 2.0 登录示例,并涵盖以下主题。

  • 初始化设置
  • 设置重定向URI
  • 配置 application.yml
  • 启动应用程序

1、初始化设置

要使用谷歌的OAuth 2.0认证系统进行登录,你必须在谷歌API控制台中设置一个项目,以获得OAuth 2.0凭证。

谷歌用于认证的 OAuth 2.0实现 符合 OpenID Connect 1.0规范,并通过了 OpenID认证。

按照 OpenID Connect 页面上的指示,从 “Setting up OAuth 2.0” 部分开始。

在完成 “Obtain OAuth 2.0 credentials” 的说明后,你应该有新的OAuth客户端,其证书包括一个 Client ID 和一个 Client Secret。

2、设置重定向URI

重定向URI是终端用户的用户代理在通过谷歌认证并在同意页面上授权访问OAuth客户端( 在上一步创建的)后,被重定向到应用程序中的路径。

在 "设置重定向URI" 小节中,确保授权的重定向URI字段被设置为 localhost:8080/login/oauth2/code/google。

默认重定向URI模板是 {baseUrl}/login/oauth2/code/{registrationId}。registrationId 是 ClientRegistration 的唯一标识符。

如果OAuth客户端在代理服务器后面运行,你应该检查 代理服务器配置,以确保应用程序的配置正确。另外,请看支持的 URI模板变量 的 redirect-uri。

3、配置 application.yml

现在你已经有了一个新的谷歌OAuth客户端,你需要配置应用程序,以使用OAuth客户端的认证流程。要做到这一点。

  1. 进入 application.yml 并设置以下配置。
  2. spring: security: oauth2: client: registration: google: client-id: google-client-id client-secret: google-client-secret
  3. Copied!
  4. OAuth Client properties
  5. spring.security.oauth2.client.registration 是OAuth客户端属性的基础属性前缀。在基本属性的前缀后面是 ClientRegistration 的ID,如Google。
  6. 将 client-id 和 client-secret 属性中的值替换为你之前创建的OAuth 2.0凭证。

4、启动应用程序

启动Spring Boot 2.x 示例应用,进入 localhost:8080。然后你会被重定向到默认的自动生成的登录页面,其中显示一个Google的链接。

点击谷歌的链接,然后你会被转到谷歌进行认证。

在用你的谷歌账户凭证进行认证后,你会看到“同意界面”。“同意界面”要求你允许或拒绝访问你先前创建的OAuth客户端。点击 Allow,授权OAuth客户端访问你的电子邮件地址和基本个人资料信息。

此时,OAuth客户端从 UserInfo Endpoint 检索你的电子邮件地址和基本个人资料信息,并建立一个已认证的会话(Session)。

二、Spring Boot 2.x 属性映射

下表列出了Spring Boot 2.x OAuth客户端属性与 ClientRegistration 属性的映射。

Spring Boot 2.x

ClientRegistration

spring.security.oauth2.client.registration.[registrationId]

registrationId

spring.security.oauth2.client.registration.[registrationId].client-id

clientId

spring.security.oauth2.client.registration.[registrationId].client-secret

clientSecret

spring.security.oauth2.client.registration.[registrationId].client-authentication-method

clientAuthenticationMethod

spring.security.oauth2.client.registration.[registrationId].authorization-grant-type

authorizationGrantType

spring.security.oauth2.client.registration.[registrationId].redirect-uri

redirectUri

spring.security.oauth2.client.registration.[registrationId].scope

scopes

spring.security.oauth2.client.registration.[registrationId].client-name

clientName

spring.security.oauth2.client.provider.[providerId].authorization-uri

providerDetails.authorizationUri

spring.security.oauth2.client.provider.[providerId].token-uri

providerDetails.tokenUri

spring.security.oauth2.client.provider.[providerId].jwk-set-uri

providerDetails.jwkSetUri

spring.security.oauth2.client.provider.[providerId].issuer-uri

providerDetails.issuerUri

spring.security.oauth2.client.provider.[providerId].user-info-uri

providerDetails.userInfoEndpoint.uri

spring.security.oauth2.client.provider.[providerId].user-info-authentication-method

providerDetails.userInfoEndpoint.authenticationMethod

spring.security.oauth2.client.provider.[providerId].user-name-attribute

providerDetails.userInfoEndpoint.userNameAttributeName

你可以通过指定 spring.security.oauth2.client.provider.[providerId].issuer-uri 属性,使用发现OpenID Connect提供者的 Configuration endpoint 或授权服务器的 Metadata endpoint 来初始配置 ClientRegistration。

二、CommonOAuth2Provider

CommonOAuth2Provider 为一些知名的供应商预先定义了一套默认的客户端属性。如:谷歌、GitHub、Facebook和Okta。

例如,authorization-uri、token-uri 和 user-info-uri 对提供者来说不会经常改变。因此,提供默认值是有意义的,可以减少所需的配置。

正如之前所展示的,当我们 配置谷歌客户端时,只需要 client-id 和 client-secret 属性。

下面列出了一个例子。

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

客户端属性的自动默认在这里工作得天衣无缝,因为 registrationId(谷歌)与 CommonOAuth2Provider 中的 GOOGLE 枚举(不区分大小写)相匹配。

对于你可能想指定一个不同的 registrationId 的情况,如 google-login,你仍然可以通过配置 provider 属性来利用客户端属性的自动默认。

下面列出了一个例子。

spring:security:oauth2:client:registration:google-login:	provider: google	client-id: google-client-idclient-secret: google-client-secret

registrationId 被设置为 google-login。

提供者属性被设置为 google,这将利用 CommonOAuth2Provider.GOOGLE.getBuilder() 中设置的客户端属性的自动默认。

三、配置自定义提供者(Provider)属性

有一些OAuth 2.0供应商支持多租户,这导致每个租户(或子域)都有不同的协议端点。

例如,在Okta注册的OAuth客户端被分配到一个特定的子域,并有他们自己的协议端点。

对于这些情况,Spring Boot 2.x为配置自定义提供者属性提供了以下基础属性:spring.security.oauth2.client.provider.[providerId]

下面列出了一个例子。

spring:security:oauth2:client:registration:okta:client-id: okta-client-idclient-secret: okta-client-secretprovider:okta:	authorization-uri: https://your-subdomain.oktapreview.com/oauth2/v1/authorizetoken-uri: https://your-subdomain.oktapreview.com/oauth2/v1/tokenuser-info-uri: https://your-subdomain.oktapreview.com/oauth2/v1/userinfouser-name-attribute: subjwk-set-uri: https://your-subdomain.oktapreview.com/oauth2/v1/keys

基础属性(spring.security.oauth2.client.provider.okta)允许自定义配置协议的端点位置。

四、覆盖 Spring Boot 2.x 的自动配置

用于支持OAuth客户端的 Spring Boot 2.x 自动配置类是 OAuth2ClientAutoConfiguration。

它执行以下任务。

  • 注册一个由配置的OAuth客户端属性的 ClientRegistrationRepository @Bean 组成的 ClientRegistration。
  • 注册一个 SecurityFilterChain @Bean,并通过 httpSecurity.oauth2Login() 启用OAuth 2.0登录。

如果你需要根据你的具体要求覆盖自动配置,你可以通过以下方式进行。

  • 注册一个 ClientRegistrationRepository @Bean
  • 注册一个 SecurityFilterChain @Bean
  • 完全覆盖自动配置

五、注册一个 ClientRegistrationRepository @Bean

下面的例子显示了如何注册一个 ClientRegistrationRepository @Bean。

  • Java
@Configuration
public class OAuth2LoginConfig {@Beanpublic ClientRegistrationRepository clientRegistrationRepository() {return new InMemoryClientRegistrationRepository(this.googleClientRegistration());}private ClientRegistration googleClientRegistration() {return ClientRegistration.withRegistrationId("google").clientId("google-client-id").clientSecret("google-client-secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).redirectUri("{baseUrl}/login/oauth2/code/{registrationId}").scope("openid", "profile", "email", "address", "phone").authorizationUri("https://accounts.google.com/o/oauth2/v2/auth").tokenUri("https://www.googleapis.com/oauth2/v4/token").userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo").userNameAttributeName(IdTokenClaimNames.SUB).jwkSetUri("https://www.googleapis.com/oauth2/v3/certs").clientName("Google").build();}
}

六、注册一个 SecurityFilterChain @Bean

下面的例子展示了如何用 @EnableWebSecurity 注册一个 SecurityFilterChain @Bean,并通过 httpSecurity.oauth2Login() 启用OAuth 2.0登录。

OAuth2 Login Configuration

  • Java
@Configuration
@EnableWebSecurity
public class OAuth2LoginSecurityConfig {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()).oauth2Login(withDefaults());return http.build();}
}

七、完全覆盖自动配置

下面的例子显示了如何通过注册一个 ClientRegistrationRepository @Bean 和一个 SecurityFilterChain @Bean 来完全覆盖自动配置。

Overriding the auto-configuration

  • Java
@Configuration
public class OAuth2LoginConfig {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()).oauth2Login(withDefaults());return http.build();}@Beanpublic ClientRegistrationRepository clientRegistrationRepository() {return new InMemoryClientRegistrationRepository(this.googleClientRegistration());}private ClientRegistration googleClientRegistration() {return ClientRegistration.withRegistrationId("google").clientId("google-client-id").clientSecret("google-client-secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).redirectUri("{baseUrl}/login/oauth2/code/{registrationId}").scope("openid", "profile", "email", "address", "phone").authorizationUri("https://accounts.google.com/o/oauth2/v2/auth").tokenUri("https://www.googleapis.com/oauth2/v4/token").userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo").userNameAttributeName(IdTokenClaimNames.SUB).jwkSetUri("https://www.googleapis.com/oauth2/v3/certs").clientName("Google").build();}
}

八、不使用 Spring Boot 2.x 的 Java 配置

如果你不能使用 Spring Boot 2.x,并希望配置 CommonOAuth2Provider 中的一个预定义提供者(例如,谷歌),请应用以下配置。

OAuth2 Login Configuration

  • Java
@Configuration
@EnableWebSecurity
public class OAuth2LoginConfig {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()).oauth2Login(withDefaults());return http.build();}@Beanpublic ClientRegistrationRepository clientRegistrationRepository() {return new InMemoryClientRegistrationRepository(this.googleClientRegistration());}@Beanpublic OAuth2AuthorizedClientService authorizedClientService(ClientRegistrationRepository clientRegistrationRepository) {return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);}@Beanpublic OAuth2AuthorizedClientRepository authorizedClientRepository(OAuth2AuthorizedClientService authorizedClientService) {return new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService);}private ClientRegistration googleClientRegistration() {return CommonOAuth2Provider.GOOGLE.getBuilder("google").clientId("google-client-id").clientSecret("google-client-secret").build();}
}

相关文章:

Spring Boot OAuth 2.0整合详解

目录 一、Spring Boot 2.x 示例 1、初始化设置 2、设置重定向URI 3、配置 application.yml 4、启动应用程序 二、Spring Boot 2.x 属性映射 二、CommonOAuth2Provider 三、配置自定义提供者(Provider)属性 四、覆盖 Spring Boot 2.x 的自动配置…...

安装visual studio报错“无法安装msodbcsql“

在安装visual studio2022时安装完成后提示无法安装msodbcsql, 查看日志文件详细信息提示:指定账户已存在。 未能安装包“msodbcsql,version17.2.30929.1,chipx64,languagezh-CN”。 搜索 URL https://aka.ms/VSSetupErrorReports?qPackageIdmsodbcsql;PackageActi…...

webGL编程指南 第三章 矩阵平移三角形.translatedTriangle_Matrix

我会持续更新关于wegl的编程指南中的代码。 当前的代码不会使用书中的缩写&#xff0c;每一步都是会展开写。希望能给后来学习的一些帮助 git代码地址 &#xff1a;git 接着 上一节 中 我们使用矩阵进行旋转&#xff0c;这次我们使用矩阵实现位移 <!DOCTYPE html> <…...

修改echarts的tooltip样式 折线图如何配置阴影并实现渐变色和自适应

图片展示 一、引入echarts 这里不用多解释 vue里使用 import echarts from “echarts”; html页面引用js文件或用script标签引用 二、定义一个具有宽高的dom div <div id"echart-broken" style"width:400px;height: 200px;"></div>三、定义…...

[论文笔记] SurroundOcc: Multi-Camera 3D Occupancy Prediction for Autonomous Driving

Wei, Yi, et al. “Surroundocc: Multi-camera 3d occupancy prediction for autonomous driving.” Proceedings of the IEEE/CVF International Conference on Computer Vision. 2023. 重点记录 将占用网格应用到多个相机构成的3D空间中; 使用BEVFormer中的方法获取3D特征, …...

辅助驾驶功能开发-功能对标篇(16)-NOA 城市辅助系统-毫末智行

1.横向对标参数 厂商毫末智行车型魏牌摩卡DHT-PHEV上市时间发布:2022年8月30日 上市:2022年底前方案12V5R2L+1DMS摄像头前视摄像头*3【800W】侧视摄像头*4后视摄像头*1【800W】环视摄像头*4DMS摄像头*1雷达毫米波雷达*54D毫米波雷达/超声波雷达*12激光雷达*2【速腾聚创 M1,1…...

H3C的IRF堆叠互联关系说明

H3C IRF堆叠互联说明48口交换机连接方式IRF Port 两台设备第一台的51口 第二台的51口irf-port 1/2 port group interface ten-gigabitethernet 1/0/51 port group interface ten-gigabitethernet 1/0/52第一台的52口第二台的52口irf-port 2/1 port group interface ten-gigabi…...

货物摆放(蓝桥杯)

货物摆放 题目描述 小蓝有一个超大的仓库&#xff0c;可以摆放很多货物。 现在&#xff0c;小蓝有 n 箱货物要摆放在仓库&#xff0c;每箱货物都是规则的正方体。小蓝规定了长、宽、高三个互相垂直的方向&#xff0c;每箱货物的边都必须严格平行于长、宽、高。 小蓝希望所有的…...

3782: 【C3】【穷举】弹珠游戏

目录 题目描述 输入 输出 样例输入 样例输出 题目描述 游戏的内容是&#xff1a;在一个 n*n 的矩阵里&#xff0c;有若干个敌人&#xff0c;你的弹珠可以摧毁敌人&#xff0c;但只能攻击你所在的行、列里的所有敌人&#xff0c;然后你就可以获得他们的分数之和&#xff0…...

leetcode 5

leetcode 5 题目是通过枚举字符串&#xff0c;然后判断是否子字符串满足回文。 引用传递和值传递相比&#xff0c;引用传递可以减少内存空间。提高代码运行效率。 https://www.cnblogs.com/yanlingyin/archive/2011/12/07/2278961.html...

centos中nacos设置开机自启动

以下实践亲测有效&#xff01; 1、在以下目录编辑新建nacos.service文件 vim /lib/systemd/system/nacos.service [Unit] Descriptionnacos Afternetwork.target [Service] Typeforking ExecStart/usr/local/nacos/bin/startup.sh -m standalone ExecReload/usr/local/nacos/b…...

双指针——移动零

一&#xff0c;题目要求&#xff1a; 给定一个数组 nums&#xff0c;编写一个函数将所有 0 移动到数组的末尾&#xff0c;同时保持非零元素的相对顺序。 请注意 &#xff0c;必须在不复制数组的情况下原地对数组进行操作。 示例 1: 输入: nums [0,1,0,3,12] 输出: [1,3,12,0,0…...

WPF中在MVVM模式下实现导航功能

WPF中在MVVM模式下实现导航功能 一、利用TabControl 使用场景&#xff1a;项目小&#xff0c;不用考虑内存开销的问题。 实现方式1-手动指定ViewModel 分别定义3个UserControl作为View用于演示 <UserControl...><Grid><StackPanel Orientation"Vertic…...

SpringBoot面试题2:SpringBoot与SpringCloud 区别?SpringBoot和Spring、SpringMVC的区别

该文章专注于面试,面试只要回答关键点即可,不需要对框架有非常深入的回答,如果你想应付面试,是足够了,抓住关键点 面试官:SpringBoot与SpringCloud 区别? Spring Boot 和 Spring Cloud 是 Spring 生态系统中的两个关键组件,它们有以下区别: 定位:Spring Boot 用于简…...

Practical Deep Raw Image Denoisingon Mobile Devices

Abstract 近年来&#xff0c;基于深度学习的图像去噪方法得到了广泛的研究&#xff0c;并在许多公共基准数据集中盛行。然而&#xff0c;最先进的网络计算成本太高&#xff0c;无法直接应用于移动设备。在这项工作中&#xff0c;我们提出了一种轻量级、高效的基于神经网络的原…...

如何在Android项目中制作和使用三方包(jar文件)

文章目录 1 概念介绍2 制作方法2.1 制作步骤2.2 制作结果3 使用方法3.1 具体步骤3.2 示例代码4 内容总结在项目中为了跨部门协作需要把相关的内容打成包文件,基于这个需求,我们将介绍如何把 代码制作成三方包,这里的三方包是指jar文件。同时也会介绍如何在Android项目中使用…...

消息队列Beanstalkd介绍

摘要&#xff1a; Beanstalkd是一个高性能、轻量级的、分布式的、内存型的消息队列系统。最初设计的目的是想通过后台异步执行耗时的任务来降低高容量Web应用系统的页面访问延迟。其实Beanstalkd是典型的类Memcached设计&#xff0c;协议和使用方式都是同样的风格。其基本设计思…...

【C++】继承 ⑥ ( 继承中的构造函数和析构函数 | 类型兼容性原则 | 父类指针 指向 子类对象 | 使用 子类对象 为 父类对象 进行初始化 )

文章目录 一、public 公有继承 - 示例分析1、类型兼容性原则2、类型兼容性原则应用场景 二、类型兼容性原则 - 示例分析1、父类指针 指向 子类对象2、使用 子类对象 为 父类对象 进行初始化3、完整代码示例 一、public 公有继承 - 示例分析 1、类型兼容性原则 类型兼容性原则 :…...

15 | JPA 对 Web MVC 开发者做了哪些支持

我们使用 Spring Data JPA 的时候&#xff0c;一般都会用到 Spring MVC&#xff0c;Spring Data 对 Spring MVC 做了很好的支持&#xff0c;体现在以下几个方面&#xff1a; 支持在 Controller 层直接返回实体&#xff0c;而不使用其显式的调用方法&#xff1b;对 MVC 层支持标…...

链表的概念+MySingleList的实现

文章目录 链表一、 链表的概念1.概念2. 结构 二、MySingleList的实现1 .定义内部类2 .创建链表3. 遍历链表并打印4.查找单链表中是否包含关键字key5.得到链表的长度6.头插法7. 尾插法8.任意位置插入8.删除结点清空 链表 顺序存储&#xff1a;顺序表/ArrayList 优点&#xff1…...

VB.net复制Ntag213卡写入UID

本示例使用的发卡器&#xff1a;https://item.taobao.com/item.htm?ftt&id615391857885 一、读取旧Ntag卡的UID和数据 Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click轻松读卡技术支持:网站:Dim i, j As IntegerDim cardidhex, …...

visual studio 2022更改主题为深色

visual studio 2022更改主题为深色 点击visual studio 上方的 工具-> 选项 在选项窗口中&#xff0c;选择 环境 -> 常规 &#xff0c;将其中的颜色主题改成深色 点击确定&#xff0c;更改完成...

YSYX学习记录(八)

C语言&#xff0c;练习0&#xff1a; 先创建一个文件夹&#xff0c;我用的是物理机&#xff1a; 安装build-essential 练习1&#xff1a; 我注释掉了 #include <stdio.h> 出现下面错误 在你的文本编辑器中打开ex1文件&#xff0c;随机修改或删除一部分&#xff0c;之后…...

srs linux

下载编译运行 git clone https:///ossrs/srs.git ./configure --h265on make 编译完成后即可启动SRS # 启动 ./objs/srs -c conf/srs.conf # 查看日志 tail -n 30 -f ./objs/srs.log 开放端口 默认RTMP接收推流端口是1935&#xff0c;SRS管理页面端口是8080&#xff0c;可…...

【C++从零实现Json-Rpc框架】第六弹 —— 服务端模块划分

一、项目背景回顾 前五弹完成了Json-Rpc协议解析、请求处理、客户端调用等基础模块搭建。 本弹重点聚焦于服务端的模块划分与架构设计&#xff0c;提升代码结构的可维护性与扩展性。 二、服务端模块设计目标 高内聚低耦合&#xff1a;各模块职责清晰&#xff0c;便于独立开发…...

MySQL账号权限管理指南:安全创建账户与精细授权技巧

在MySQL数据库管理中&#xff0c;合理创建用户账号并分配精确权限是保障数据安全的核心环节。直接使用root账号进行所有操作不仅危险且难以审计操作行为。今天我们来全面解析MySQL账号创建与权限分配的专业方法。 一、为何需要创建独立账号&#xff1f; 最小权限原则&#xf…...

腾讯云V3签名

想要接入腾讯云的Api&#xff0c;必然先按其文档计算出所要求的签名。 之前也调用过腾讯云的接口&#xff0c;但总是卡在签名这一步&#xff0c;最后放弃选择SDK&#xff0c;这次终于自己代码实现。 可能腾讯云翻新了接口文档&#xff0c;现在阅读起来&#xff0c;清晰了很多&…...

Git 3天2K星标:Datawhale 的 Happy-LLM 项目介绍(附教程)

引言 在人工智能飞速发展的今天&#xff0c;大语言模型&#xff08;Large Language Models, LLMs&#xff09;已成为技术领域的焦点。从智能写作到代码生成&#xff0c;LLM 的应用场景不断扩展&#xff0c;深刻改变了我们的工作和生活方式。然而&#xff0c;理解这些模型的内部…...

go 里面的指针

指针 在 Go 中&#xff0c;指针&#xff08;pointer&#xff09;是一个变量的内存地址&#xff0c;就像 C 语言那样&#xff1a; a : 10 p : &a // p 是一个指向 a 的指针 fmt.Println(*p) // 输出 10&#xff0c;通过指针解引用• &a 表示获取变量 a 的地址 p 表示…...

FFmpeg avformat_open_input函数分析

函数内部的总体流程如下&#xff1a; avformat_open_input 精简后的代码如下&#xff1a; int avformat_open_input(AVFormatContext **ps, const char *filename,ff_const59 AVInputFormat *fmt, AVDictionary **options) {AVFormatContext *s *ps;int i, ret 0;AVDictio…...