springboot 2.7 oauth server配置源码走读一

springboot 2.7 oauth server配置源码走读

入口:
在这里插入图片描述
上述截图中的方法签名和OAuth2AuthorizationServerConfiguration类中的一个方法一样,只不过我们自己的配置类优先级比spring中的配置类低,算是配置覆盖,看下图所示:
在这里插入图片描述
它们都提到了 OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
所以我们分析它:
在这里插入图片描述
一. new出来的OAuth2AuthorizationServerConfigurer:
官方声称它是:An AbstractHttpConfigurer for OAuth 2.0 Authorization Server support.(一个用于OAuth 2.0 授权服务器的抽象配置类)。
从源码中可以看到它“管理”着以下具体配置类:
在这里插入图片描述
先给出结论:这些配置类endpoint访问默认值对应如下(如何推导请耐心往下看):
在这里插入图片描述
我们具体看下上述第77行:getRequestMatcher(OAuth2TokenEndpointConfigurer.class).matches(request) 的实现:
我们可以看到第一条绿色下划线:tokenEndpoint的来源,等下我们再去探究它:
在这里插入图片描述
所以我们去AntPathRequestMatcher类 查看实现:
可以看到用到了策略模式:根据pattern (/**表示MATCH_ALL)不同,初始化的matcher也不同:
在这里插入图片描述
接下来我们可以看上述第一条绿色下划线:tokenEndpoint的来源,现在去探究它:

ProviderSettings:它是一个配置类,继承于AbstractSettings(接下来我们自己配置中用到的TokenSettings+ClientSettings类也继承于它),如下所求,我们可以指定token endpoint(当然还有授权,introspection等等),
在这里插入图片描述

如果不指定,则默认配置如下:注意 /oauth2/jwks, 后面resource-server就可以指定它来验证token的有效性。
在这里插入图片描述

那ProvideSettings如何初始化呢?又是和配置类关联起来?
1.构造方法中传递:
在这里插入图片描述
2.在我们的配置类中流入bean(官方示例也是这么做的):
在这里插入图片描述

然后看源码:
在这里插入图片描述

其中providerSettings.getJwkSetEndpoint()我们上面看过,如果没有指定配置,则默认值为:
/oauth2/jwks
在这里插入图片描述
二. 我们配置类中的其它配置:
在这里插入图片描述
上述2个配置方法在OAuth2AuthorizationServerConfiguration类中也可以找到类似的方法,如下所示:
在这里插入图片描述
三.最后把完整的oauth2 server配置如下:

package com.jel.tech.auth.config;import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.ClientSettings;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.oauth2.server.authorization.config.TokenSettings;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.time.Duration;
import java.util.UUID;/*** @author: jelex.xu* @Date: 2024/1/2 18:31* @desc:**/
@Configuration
public class OAuth2AuthorizeSecurityConfig {/*** 重写:org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration*          #authorizationServerSecurityFilterChain(HttpSecurity)* @param http* @return* @throws Exception*/@Bean@Order(1)public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);return http.formLogin(Customizer.withDefaults()).build();}@Bean@Order(2)public SecurityFilterChain standardSecurityFilterChain(HttpSecurity http) throws Exception {// @formatter:offhttp.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()).formLogin(Customizer.withDefaults());// @formatter:onreturn http.build();}@Beanpublic RegisteredClientRepository registeredClientRepository() {RegisteredClient loginClient = RegisteredClient.withId(UUID.randomUUID().toString()).clientId("login-client").clientSecret("{noop}openid-connect").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN).redirectUri("http://127.0.0.1:8080/login/oauth2/code/login-client").redirectUri("http://127.0.0.1:8080/authorized").scope(OidcScopes.OPENID).scope(OidcScopes.PROFILE).clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()).build();RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString()).clientId("messaging-client").clientSecret("{noop}secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).scope("message:read").scope("message:write")// 指定token有效期:token:30分(默认5分钟),refresh_token:1天.tokenSettings(TokenSettings.builder().accessTokenTimeToLive(Duration.ofMinutes(30)).refreshTokenTimeToLive(Duration.ofDays(1)).build())
//                .id("xxx").build();return new InMemoryRegisteredClientRepository(loginClient, registeredClient);}@Beanpublic JWKSource<SecurityContext> jwkSource(KeyPair keyPair) {RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();RSAKey rsaKey = new RSAKey.Builder(publicKey).privateKey(privateKey).keyID(UUID.randomUUID().toString()).build();JWKSet jwkSet = new JWKSet(rsaKey);return new ImmutableJWKSet<>(jwkSet);}@Beanpublic JwtDecoder jwtDecoder(KeyPair keyPair) {return NimbusJwtDecoder.withPublicKey((RSAPublicKey) keyPair.getPublic()).build();}@Beanpublic ProviderSettings providerSettings() {return ProviderSettings.builder().issuer("http://127.0.0.1:9000").build();}@Beanpublic UserDetailsService userDetailsService() {PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();// outputs {bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG// remember the password that is printed out and use in the next stepSystem.out.println(encoder.encode("password"));UserDetails userDetails = User.withUsername("user").username("user").password("{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG").roles("USER").build();return new InMemoryUserDetailsManager(userDetails);}@Bean@Role(BeanDefinition.ROLE_INFRASTRUCTURE)KeyPair generateRsaKey() {KeyPair keyPair;try {KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");keyPairGenerator.initialize(2048);keyPair = keyPairGenerator.generateKeyPair();return keyPair;} catch (NoSuchAlgorithmException e) {throw new IllegalArgumentException(e);}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/611497.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

阿里云国际服务器设置安全防护程序

阿里云云服务器&#xff08;ECS&#xff09;提供弹性、安全、高性能、高性价比的虚拟云服务器&#xff0c;满足您的所有需求。立即在这里免费注册&#xff01; 常见 Web 应用程序 请勿对 Web 服务控制台&#xff08;如 WDCP、TOMCAT、Apache、Nginx、Jekins、PHPMyAdmin、Web…

JavaScript数组sort()对负数排序的陷阱

前言 想着好久没去力扣刷题了&#xff0c;刚好手上的需求也差不多了&#xff0c;就去看了看。看到一个难度级别为困难的题&#xff0c;看到这个题想着直接使用JS现成的方法&#xff0c;先concat再sort。再取中间值不就实现了吗。是不是你们也这么想&#xff0c;哈哈哈。 就是…

11 个 Python全栈开发工具集

前言 以下是专注于全栈开发不同方面的 Python 库;有些专注于 Web 应用程序开发&#xff0c;有些专注于后端&#xff0c;而另一些则两者兼而有之。 1. Taipy Taipy 是一个开源的 Python 库&#xff0c;用于构建生产就绪的应用程序前端和后端。 它旨在加快应用程序开发&#xf…

2024--Django平台开发-Django知识点(五)

day05 django知识点 今日概要&#xff1a; 中间件 【使用】【源码】cookie 【使用】【源码 - Django底层请求本质】session【使用】【源码 - 数据库请求周期中间件】 1.中间件 1.1 使用 编写类&#xff0c;在类型定义&#xff1a;process_request、process_view、process_…

【C++】STL 算法 ⑨ ( 预定义函数对象示例 - 将容器元素从大到小排序 | sort 排序算法 | greater<T> 预定义函数对象 )

文章目录 一、预定义函数对象示例 - 将容器元素从大到小排序1、sort 排序算法2、greater<T> 预定义函数对象 二、代码示例 - 预定义函数对象1、代码示例2、执行结果 一、预定义函数对象示例 - 将容器元素从大到小排序 1、sort 排序算法 C 标准模板库 ( STL , Standard Te…

离散数学-二元关系

4.1关系的概念 1)序偶及n元有序组 由两个个体x和y&#xff0c;按照一定顺序排序成的、有序数组称为有序偶或有序对、二元有序组&#xff0c; 记作<x&#xff0c;y>&#xff0c;其中x是第一分量&#xff0c;y是第二分量。 相等有序偶&#xff1a;第一分量和第二分量分…

游戏开发中,你的游戏图片压缩格式使用ASTC了吗

文章目录 ASTC原理&#xff1a;使用要求 ASTC&#xff08;Adaptive Scalable Texture Compression&#xff0c;自适应可伸缩纹理压缩&#xff09;是一种高级的纹理压缩技术&#xff0c;由ARM公司开发并推广。它在图形处理领域中因其出色的压缩效率和灵活性而受到广泛关注。 AST…

前端国际化之痛点(二):多包多库场景下联动多语言

前言 VoerkaI18n是一款非常优秀的前端国际化解决方案&#xff0c;其开发的出发点是为了解决现存多语言的一些痛点,接下来几篇文章将分别进行分析。 前端国际化之痛点(一)&#xff1a;让人头疼的词条Key前端国际化之痛点(二)&#xff1a;多包多库场景下联动多语言前端国际化之…

Jetson Orin AGX 64GB更新 Jetpack6.0

Jetson Orin AGX 64GB更新 Jetpack6.0 注意&#xff1a; 1&#xff0c;如果你要向我一样为AGX更新Jetpack6.0的话&#xff0c;它还要求你的ubuntu版本必须是20.04 或22.04 2&#xff0c;安装完SDKmanager后&#xff0c;然后选择对应的设备&#xff0c;根据个人选择勾选是否安装…

【Mysql】InnoDB 引擎中的页目录

一、页目录和槽 现在知道记录在页中按照主键大小顺序串成了单链表。 那么我使用主键查询的时候&#xff0c;最顺其自然的办法肯定是从第一条记录&#xff0c;也就是 Infrimum 记录开始&#xff0c;一直向后找&#xff0c;只要存在总会找到。这种在数据量少的时候还好说&#x…

四、K8S-Deployment(无状态服务)

目录 一、引入Deployment 二、Deployment资源清单 三、Deployment支持的功能 1、扩缩容 1、通过命令行方式修改 2 、在线编辑yaml文件方式修改 2、镜像更新 1、重建更新 2、滚动更新 3、金丝雀发布&#xff08;灰度更新&#xff09; [rootk8s-master-1 ~]# kubectl g…

centos用yum安装mysql详细教程

1 查询安装mysql的yum源,命令如下 ls /etc/yum.repos.d/ -l 界面如下图所示&#xff0c;未显示mysql的安装源 2 安装mysql相关的yum源,例如&#xff1a; 例如&#xff1a;rpm -ivh mysql57-community-release-el7.rpm 要注意 mysql的版本和系统的版本匹配 mysql57-communi…

【高等数学之泰勒公式】

一、从零开始 1.1、泰勒中值定理1 什么是泰勒公式?我们先看看权威解读: 那么我们从古至今到底是如何创造出泰勒公式的呢? 由上图可知&#xff0c;任一无穷小数均可以表示成用一系列数字的求和而得出的结果&#xff0c;我们称之为“无穷算法”。 那么同理我们想对任一曲线来…

Qt/QML编程学习之心得:hicar手机投屏到车机中控的实现(32)

hicar,是华为推出的一款手机APP,有百度地图、华为音乐,更多应用中还有很多对应手机上装在的其他APP,都可以在这个里面打开使用,对开车的司机非常友好。但它不仅仅是用在手机上,它还可以投屏到车机中控上,这是比较神奇的一点。 HiCar本质上是一套智能投屏系统,理论上所有…

springboot 企业微信 网页授权

html 引入jquery $(function () {// alert("JQ onready");// 当前企业的 corp_idconst corp_id xxxxxx;// 重定向 URL → 最终打开的画面地址&#xff0c;域名是在企业微信上配置好的域名const redirect_uri encodeURI(http://xxxxx.cn);//企业的agentId 每个应用都…

Vue3-39-路由-导航异常的检测 afterEatch 与 编程式导航之后的订阅动作

说明 本文主要是介绍一下 路由的后置守卫 afterEatch 的一个重要的作用 &#xff1a; 就是检测路由异常信息。 它的实现方式是 通过第三个参数来返回的。 而且&#xff0c;它的异常检测是全局的。导航的异常有以下三种类型&#xff1a; aborted : 在导航守卫中 被拦截并返回了…

【Blog】记录一下如何让自己的自建网站让百度搜索收录

记录一下如何让自己的自建网站让百度搜索收录 目录 记录一下如何让自己的自建网站让百度搜索收录一、前言二、开始操作1、第一步&#xff1a;进入设置2、第二步&#xff1a;开始设置3、第三步&#xff1a;让百度收录我们自己的文章 三、知识点记录1、注意事项2、可能会出现的问…

vsCode输出控制台中文乱码解决

在tasks.json里的args中添加 "-fexec-charsetGBK", // 处理mingw中文编码问题 "-finput-charsetUTF-8",// 处理mingw中文编码问题

PyCharm 设置新建Python文件时自动在文章开头添加固定注释的方法

在实际项目开发时&#xff0c;为了让编写的每个代码文件易读、易于维护或方便协同开发时&#xff0c;我们都会在每一个代码文件的开头做一些注释&#xff0c;如作者&#xff0c;文档编写时间&#xff0c;文档的功能说明等。 利用PyCharm 编辑器&#xff0c;我们只需设置相关设…

微机原理常考简答题总结

一&#xff0c;8086和8088这两个微处理器在结构上有什么异同&#xff1f; &#xff08;1&#xff09;共同点&#xff1a;内部均由EU、BIU组成&#xff0c;结构基本相同&#xff1b;寄存器等功能部件均为16位&#xff1b;内部数据通路为16位&#xff1b;指令系统相同。 &#x…