Spring Securit OAuth 2.0整合—核心的接口和类

目录

一、ClientRegistration

二、ClientRegistrationRepository

三、OAuth2AuthorizedClient

四、OAuth2AuthorizedClientRepository 和 OAuth2AuthorizedClientService

五、OAuth2AuthorizedClientManager 和 OAuth2AuthorizedClientProvider


一、ClientRegistration

ClientRegistration 是一个在 OAuth 2.0 或 OpenID Connect 1.0 提供商(Provider)处注册的客户端的表示。

ClientRegistration 对象保存的信息包括客户端ID、客户端 secret、授权类型、重定向URI、scope、授权URI、token URI 和其他详细信息。

ClientRegistration 和它的属性定义如下。

public final class ClientRegistration {private String registrationId;	private String clientId;	private String clientSecret;	private ClientAuthenticationMethod clientAuthenticationMethod;	private AuthorizationGrantType authorizationGrantType;	private String redirectUri;	private Set<String> scopes;	private ProviderDetails providerDetails;private String clientName;	public class ProviderDetails {private String authorizationUri;	private String tokenUri;	private UserInfoEndpoint userInfoEndpoint;private String jwkSetUri;	private String issuerUri;	private Map<String, Object> configurationMetadata;  public class UserInfoEndpoint {private String uri;	private AuthenticationMethod authenticationMethod;  private String userNameAttributeName;	}}
}

registrationId: 唯一能识别 ClientRegistration 的ID。

clientId: 客户端ID

clientSecret: 客户端 Secret。

clientAuthenticationMethod: 用于验证客户和提供者的方法。支持的值是 client_secret_basic, client_secret_post, private_key_jwt, client_secret_jwtnone( public clients)。

authorizationGrantType: OAuth 2.0授权框架定义了 四种授权许可 类型。支持的值是 authorization_code、client_credentials、password,以及扩展许可类型 urn:ietf:params:oauth:grant-type:jwt-bearer。

redirectUri: 客户端注册的重定向URI,授权服务器(Authorization Server)在终端用户认证和授权访问客户端后,将终端用户的用户代理(user-agent)重定向至此。

scopes: 客户端在授权请求流程中要求的范围(scope),如openid、电子邮件或个人资料。

clientName: 用于客户端的描述性名称。这个名字可以在某些情况下使用,比如在自动生成的登录页面中显示客户的名字。

authorizationUri: 授权服务器的授权端点URI。

tokenUri: 授权服务器的令牌(Token)端点URI。

jwkSetUri: 用于从授权服务器检索 JSON Web Key (JWK) 集的URI,其中包含用于验证ID令牌的 JSON Web Signature (JWS) 和(可选)用户信息响应的加密密钥。

issuerUri: 返回 OpenID Connect 1.0 提供者或 OAuth 2.0 授权服务器的签发者标识符URI。

configurationMetadata: OpenID 提供者配置信息。只有在配置了 Spring Boot 2.x 属性 spring.security.oauth2.client.provider.[providerId].issuerUri 时,此信息才可用。

(userInfoEndpoint)uri: UserInfo 端点 URI,用于访问认证的最终用户的claim和属性。

(userInfoEndpoint)authenticationMethod: 向 UserInfo 端点发送访问令牌时使用的认证方法。支持的值是 headerformquery

userNameAttributeName: UserInfo 响应中返回的引用最终用户的名称或标识符的属性的名称。

你可以通过发现 OpenID Connect Provider 的 配置端点 或授权服务器的 元数据端点 来初始配置 ClientRegistration。

ClientRegistrations 提供了方便的方法,以如下这种方式配置 ClientRegistration。

  • Java
ClientRegistration clientRegistration =ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build();

前面的代码依次查询了 idp.example.com/issuer/.well-known/openid-configuration、idp.example.com/.well-known/openid-configuration/issuer、idp.example.com/.well-known/oauth-authorization-server/issuer,在第一个返回200响应的地方停止。

作为一个替代方案,你可以使用 ClientRegistrations.fromOidcIssuerLocation() 只查询 OpenID Connect Provider 的配置端点。

二、ClientRegistrationRepository

ClientRegistrationRepository 作为OAuth 2.0 / OpenID Connect 1.0 ClientRegistration 的存储库(repository)。

客户端注册信息最终由相关的授权服务器存储和拥有。这个存储库提供了检索主要客户注册信息子集的能力,这些信息存储在授权服务器上。

Spring Boot 2.x的自动配置将 spring.security.oauth2.client.registration.[registrationId] 下的每个属性绑定到 ClientRegistration 实例上,然后将每个 ClientRegistration 实例组合到 ClientRegistrationRepository 中。

ClientRegistrationRepository 的默认实现是 InMemoryClientRegistrationRepository。

自动配置也将 ClientRegistrationRepository 注册为 ApplicationContext 中的 @Bean,这样,如果应用程序需要,它就可以进行依赖注入。

下面的列表显示了一个例子。

  • Java
@Controller
public class OAuth2ClientController {@Autowiredprivate ClientRegistrationRepository clientRegistrationRepository;@GetMapping("/")public String index() {ClientRegistration oktaRegistration =this.clientRegistrationRepository.findByRegistrationId("okta");...return "index";}
}

三、OAuth2AuthorizedClient

OAuth2AuthorizedClient 是一个授权客户端的代表。当终端用户(资源所有者)已经授权给客户端访问其受保护的资源时,客户端就被认为是被授权的。

OAuth2AuthorizedClient 的作用是将 OAuth2AccessToken(和可选的 OAuth2RefreshToken)与 ClientRegistration(client)和资源所有者联系起来,后者是许可授权的主要终端用户。

四、OAuth2AuthorizedClientRepository 和 OAuth2AuthorizedClientService

OAuth2AuthorizedClientRepository 负责在网络请求之间持久保存`OAuth2AuthorizedClient`,而 OAuth2AuthorizedClientService 的主要作用是在应用层面管理 OAuth2AuthorizedClient。

从开发者的角度来看,OAuth2AuthorizedClientRepository 或 OAuth2AuthorizedClientService 提供了查询与客户端相关的 OAuth2AccessToken 的能力,从而可以用来启动受保护资源的请求。

下面的列表显示了一个例子。

  • Java
@Controller
public class OAuth2ClientController {@Autowiredprivate OAuth2AuthorizedClientService authorizedClientService;@GetMapping("/")public String index(Authentication authentication) {OAuth2AuthorizedClient authorizedClient =this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName());OAuth2AccessToken accessToken = authorizedClient.getAccessToken();...return "index";}
}

Spring Boot 2.x的自动配置在 ApplicationContext 中注册了一个 OAuth2AuthorizedClientRepository 或一个 OAuth2AuthorizedClientService @Bean。但是,应用程序可以覆盖并注册一个自定义的 OAuth2AuthorizedClientRepository 或 OAuth2AuthorizedClientService @Bean。

OAuth2AuthorizedClientService 的默认实现是 InMemoryOAuth2AuthorizedClientService,它在内存中存储 OAuth2AuthorizedClient 对象。

另外,你可以配置JDBC实现 JdbcOAuth2AuthorizedClientService,将 OAuth2AuthorizedClient 实例持久化在数据库中。

JdbcOAuth2AuthorizedClientService 依赖于 OAuth 2.0 Client Schema 中描述的表定义。

五、OAuth2AuthorizedClientManager 和 OAuth2AuthorizedClientProvider

OAuth2AuthorizedClientManager 负责 OAuth2AuthorizedClient 的整体管理。

其主要职责包括

  • 通过使用 OAuth2AuthorizedClientProvider,授权(或重新授权)一个OAuth 2.0客户端。
  • 委托一个 OAuth2AuthorizedClient 的持久性,通常是通过使用一个 OAuth2AuthorizedClientService 或 OAuth2AuthorizedClientRepository 。
  • 当一个OAuth 2.0客户端被成功授权(或重新授权)时,委托给一个 OAuth2AuthorizationSuccessHandler。
  • 当OAuth2.0客户端无法授权(或重新授权)时,委托给一个 OAuth2AuthorizationFailureHandler。

一个 OAuth2AuthorizedClientProvider 实现了授权(或重新授权)OAuth 2.0客户端的策略。实现通常实现一个授权许可类型,如 authorization_code、 client_credentials 等。

OAuth2AuthorizedClientManager 的默认实现是 DefaultOAuth2AuthorizedClientManager,它与一个 OAuth2AuthorizedClientProvider 相关联,该 Provider 可以使用基于 delegation 的复合方式支持多种授权许可类型。你可以使用 OAuth2AuthorizedClientProviderBuilder 来配置和建立基于 delegation 的复合。

下面的代码显示了一个如何配置和构建 OAuth2AuthorizedClientProvider 复合体的例子,它提供了对 authorization_code、refresh_token、 client_credentials 和 password 授权许可类型的支持。

  • Java
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(ClientRegistrationRepository clientRegistrationRepository,OAuth2AuthorizedClientRepository authorizedClientRepository) {OAuth2AuthorizedClientProvider authorizedClientProvider =OAuth2AuthorizedClientProviderBuilder.builder().authorizationCode().refreshToken().clientCredentials().password().build();DefaultOAuth2AuthorizedClientManager authorizedClientManager =new DefaultOAuth2AuthorizedClientManager(clientRegistrationRepository, authorizedClientRepository);authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);return authorizedClientManager;
}

当授权尝试成功时,DefaultOAuth2AuthorizedClientManager 委托给 OAuth2AuthorizationSuccessHandler,后者(默认)通过 OAuth2AuthorizedClientRepository 保存 OAuth2AuthorizedClient。在重新授权失败的情况下(例如,刷新令牌不再有效),先前保存的 OAuth2AuthorizedClient 会通过 RemoveAuthorizedClientOAuth2AuthorizationFailureHandler 从 OAuth2AuthorizedClientRepository 中删除。你可以通过 setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler) 和 setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler) 自定义默认行为。

DefaultOAuth2AuthorizedClientManager 还与一个类型为 Function<OAuth2AuthorizeRequest, Map<String, Object> 的 contextAttributesMapper 相关联,它负责将 OAuth2AuthorizeRequest 中的属性映射到与 OAuth2AuthorizationContext 相关联的属性Map中。当你需要向 OAuth2AuthorizedClientProvider 提供所需的(支持的)属性时,这可能很有用,例如,PasswordOAuth2AuthorizedClientProvider 要求资源所有者的用户名和密码在 OAuth2AuthorizationContext.getAttributes() 中可用。

下面的代码显示了 contextAttributesMapper 的一个例子。

  • Java
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(ClientRegistrationRepository clientRegistrationRepository,OAuth2AuthorizedClientRepository authorizedClientRepository) {OAuth2AuthorizedClientProvider authorizedClientProvider =OAuth2AuthorizedClientProviderBuilder.builder().password().refreshToken().build();DefaultOAuth2AuthorizedClientManager authorizedClientManager =new DefaultOAuth2AuthorizedClientManager(clientRegistrationRepository, authorizedClientRepository);authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);// Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters,// map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`authorizedClientManager.setContextAttributesMapper(contextAttributesMapper());return authorizedClientManager;
}private Function<OAuth2AuthorizeRequest, Map<String, Object>> contextAttributesMapper() {return authorizeRequest -> {Map<String, Object> contextAttributes = Collections.emptyMap();HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD);if (StringUtils.hasText(username) && StringUtils.hasText(password)) {contextAttributes = new HashMap<>();// `PasswordOAuth2AuthorizedClientProvider` requires both attributescontextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);}return contextAttributes;};
}

DefaultOAuth2AuthorizedClientManager 被设计为在 HttpServletRequest 的上下文中(context)使用。当在 HttpServletRequest 上下文之外操作时,请使用 AuthorizedClientServiceOAuth2AuthorizedClientManager 代替。

对于何时使用 AuthorizedClientServiceOAuth2AuthorizedClientManager,服务应用是一个常见的用例。服务应用程序通常在后台运行,没有任何用户互动,并且通常在系统级账户而不是用户账户下运行。一个配置了 client_credentials 授予类型的OAuth 2.0客户端可以被认为是一种服务应用程序。

下面的代码显示了一个如何配置 AuthorizedClientServiceOAuth2AuthorizedClientManager 的例子,它提供对 client_credentials 授予类型的支持。

  • Java
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(ClientRegistrationRepository clientRegistrationRepository,OAuth2AuthorizedClientService authorizedClientService) {OAuth2AuthorizedClientProvider authorizedClientProvider =OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials().build();AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager =new AuthorizedClientServiceOAuth2AuthorizedClientManager(clientRegistrationRepository, authorizedClientService);authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);return authorizedClientManager;
}

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

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

相关文章

微服务docker部署实战

docker基础和进阶(*已掌握的可以跳过 *) 基础 docker基础 进阶 docker进阶 准备工作 提前准备好mysql和redis的配置&#xff0c;如下 在/zzq/mysql/conf目录下配置mysql配置文件my.cnf [client] #设置客户端字符集 default_character_setutf8 [mysqld] #开启定时任务 event_s…

微信小程序4

一自定义组件应用 1.介绍 微信小程序自定义组件是指开发者可以自定义组件&#xff0c;将一些常用的 UI 元素封装成一个自定义组件&#xff0c;然后在多个页面中复用该组件&#xff0c;实现代码复用和页面性能优化的效果。 2.自定义组件分为两种类型 组件模板类型&#xff1a;…

【14】基础知识:React - redux

一、 redux理解 1、学习文档 英文文档&#xff1a;https://redux.js.org/ 中文文档&#xff1a;http://www.redux.org.cn/ Github: https://github.com/reactjs/redux 2、redux是什么 redux 是一个专门用于做状态管理的 JS 库(不是 react 插件库)。 它可以用在 react&am…

求助C语言大佬:C语言的main函数参数问题

最近在敲代码的过程中&#xff0c;突发奇想&#xff0c;产生了一个疑问&#xff1a; 为什么main函数可以任由我们定义&#xff1a;可以接收一个参数、两个参数、三个参数都接接收&#xff0c;或者可以不接收&#xff1f;这是如何实现的 int main(){retrun 0; } int main (int…

怎么使用LightPicture开源搭建图片管理系统并远程访问?【搭建私人图床】

文章目录 1.前言2. Lightpicture网站搭建2.1. Lightpicture下载和安装2.2. Lightpicture网页测试2.3.cpolar的安装和注册 3.本地网页发布3.1.Cpolar云端设置3.2.Cpolar本地设置 4.公网访问测试5.结语 1.前言 现在的手机越来越先进&#xff0c;功能也越来越多&#xff0c;而手机…

TSINGSEE智慧港口可视化智能监管解决方案,助力港口码头高效监管

一、方案背景 全球经济一体化进程以及国际市场的不断融合&#xff0c;使得港口码头成为了大型货运周转中心&#xff0c;每天数以百计的大型货轮、数以千计的大型集装箱、数以万计的人员流动。港口作为货物、集装箱堆放及中转机构&#xff0c;具有昼夜不歇、天气多变、环境恶劣…

rust学习—— 控制流if 表达式

控制流 根据条件是否为真来决定是否执行某些代码&#xff0c;或根据条件是否为真来重复运行一段代码&#xff0c;是大部分编程语言的基本组成部分。Rust 代码中最常见的用来控制执行流的结构是 if 表达式和循环。 if 表达式 if 表达式允许根据条件执行不同的代码分支。你提供…

axios引入的详细讲解

1.安装axios&#xff1a;npm install axios&#xff0c;等待安装完毕即可 2.引用axios&#xff1a;在需要使用的页面中引用 import axios from axios 即可 axios请求的时候有两种方式&#xff1a;一种是get请求&#xff0c;另一种是post请求 get请求&#xff1a; axios({…

c: Queue Calling in Ubuntu

/*** file TakeNumber.h* author your name (geovindu)* brief * version 0.1* date 2023-10-20* * copyright Copyright (c) 2023 站在巨人的肩膀上 Standing on the Shoulders of Giants* */#ifndef TAKENUMBER_H #define TAKENUMBER_H#include <stdio.h> #include <…

nginx 内存管理(一)

文章目录 前提知识nginx内存管理的基础内存分配不初始化封装malloc初始化malloc 内存池内存池结构清理函数cleanup大块内存large 创建内存池申请内存void *ngx_palloc(ngx_pool_t *pool, size_t size)void *ngx_pnalloc(ngx_pool_t *pool, size_t size)void *ngx_pcalloc(ngx_p…

JS动态参数arguments与剩余参数

arguments是函数内部内置的伪数组变量&#xff0c;它包含了调用函数时传入的所以实参 让我为大家介绍一下arguments吧 平时我们获取实参&#xff1a; function fun(a, b) {console.log(a) //1console.log(b) //2}fun(1, 2)接下来我们来使用一下arguments动态获取实参 function …

6 个可解锁部分 GPT-4 功能的 Chrome 扩展(无需支付 ChatGPT Plus 费用)

在过去的几个月里&#xff0c;我广泛探索了 ChatGPT 的所有可用插件。在此期间&#xff0c;我发现了一些令人惊叹的插件&#xff0c;它们改进了我使用 ChatGPT 的方式&#xff0c;但现在&#xff0c;我将透露一些您需要了解的内容。 借助 Chrome 扩展程序&#xff0c;所有 Chat…

Ubuntu(kylin)挂载iso文件和配置apt本地源

版本说明:Ubuntu Server 16.04 LTS解决问题:解决在无任何互联网的环境下,安装软件时缺少依赖包的问题 方法一:通过虚拟机挂载 将镜像挂载到虚拟机以VMware Workstation为例,打开“虚拟机设置”,点击“CD/DVD”选项,将 “设备状态”中的“<

【插入----在第i个结点前插入值为e的新结点,删除----删除第i个结点,单链表上的查找,插入,删除算法时间效率分析】

文章目录 单链表的基本操作插入----在第i个结点前插入值为e的新结点删除----删除第i个结点单链表上的查找&#xff0c;插入&#xff0c;删除算法时间效率分析 单链表的基本操作 插入----在第i个结点前插入值为e的新结点 【算法步骤】 1.首先找到a&#xff08;i-1&#xff09;…

安全运营工程师面经

lz作为秋招狗&#xff0c;面了N场面试&#xff0c;腾讯的面试官给人的感觉就很好&#xff0c;比较懂技术&#xff0c;对项目技术问的很深 由于lz项目经验很丰富&#xff0c;因此几乎没怎么问八股文&#xff0c;主要针对项目提问&#xff0c;下面是一些主要的问题 对中间人攻击…

JavaScript基础——练习巩固题目(1)

1、获取用户信息 依次询问并获取用户的姓名、年龄、性别&#xff0c;收集数据之后在控制台依次打印出来。 提示&#xff1a; 通过prompt来弹出提示框&#xff0c;收集用户信息 通过变量保存数据 2、增加年龄 询问用户年龄&#xff0c;用户输入年龄后&#xff0c;把用户输入的…

单片机判断语句与位运算的坑

一.问题描述 在我判断Oled的某点的值是否为1时,用到了如下判断语句 if(oled[x][y/8] &1<<(y%8)但是,当我将其改为如下的判断语句,代码却跑出BUG了 if((oled[x][y/8]&1<<(y%8))1)二.原因分析 1.if语句理解错误 首选让我们看看下面的代码运行结果 #inc…

sqlsever解决传入参数过多的一种思路

问题 com.microsoft.sqlserver.jdbc.SQLServerException: 传入的请求具有过多的参数。该服务器支持最多 2100 个参数。请减少参数的数目&#xff0c;然后重新发送该请求。 方案 java sqlsever 或 sqlsever存储过程 方案1 java sqlsever 解决方案 1. 将数据处理成XML格式 …

Django中ORM框架的各个操作

我们会好奇&#xff0c;python这么简洁的语言&#xff0c;数据查询是如何做的呢&#xff1f;我将进一步详细和深入地介绍Django中ORM框架的各个方面&#xff0c;包括MySQL的增删改查和复杂查询。让我们分步骤进行。 ORM框架介绍 Django的ORM框架是一个用于与数据库进行交互的工…

Stable Diffusion WebUI扩展a1111-sd-webui-tagcomplete之Booru风格Tag自动补全功能详细介绍

安装地址 直接附上地址先: Ranting8323 / A1111 Sd Webui Tagcomplete GitCodeGitCode——开源代码托管平台,独立第三方开源社区,Git/Github/Gitlabhttps://gitcode.net/ranting8323/a1111-sd-webui-tagcomplete.git上面是GitCode的地址,下面是GitHub的地址,根据自身情…