• 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 和它的属性定义如下。

    1. public final class ClientRegistration {
    2. private String registrationId;
    3. private String clientId;
    4. private String clientSecret;
    5. private ClientAuthenticationMethod clientAuthenticationMethod;
    6. private AuthorizationGrantType authorizationGrantType;
    7. private String redirectUri;
    8. private Set<String> scopes;
    9. private ProviderDetails providerDetails;
    10. private String clientName;
    11. public class ProviderDetails {
    12. private String authorizationUri;
    13. private String tokenUri;
    14. private UserInfoEndpoint userInfoEndpoint;
    15. private String jwkSetUri;
    16. private String issuerUri;
    17. private Map<String, Object> configurationMetadata;
    18. public class UserInfoEndpoint {
    19. private String uri;
    20. private AuthenticationMethod authenticationMethod;
    21. private String userNameAttributeName;
    22. }
    23. }
    24. }

    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
    1. ClientRegistration clientRegistration =
    2. 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
    1. @Controller
    2. public class OAuth2ClientController {
    3. @Autowired
    4. private ClientRegistrationRepository clientRegistrationRepository;
    5. @GetMapping("/")
    6. public String index() {
    7. ClientRegistration oktaRegistration =
    8. this.clientRegistrationRepository.findByRegistrationId("okta");
    9. ...
    10. return "index";
    11. }
    12. }

    三、OAuth2AuthorizedClient

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

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

    四、OAuth2AuthorizedClientRepository 和 OAuth2AuthorizedClientService

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

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

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

    • Java
    1. @Controller
    2. public class OAuth2ClientController {
    3. @Autowired
    4. private OAuth2AuthorizedClientService authorizedClientService;
    5. @GetMapping("/")
    6. public String index(Authentication authentication) {
    7. OAuth2AuthorizedClient authorizedClient =
    8. this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName());
    9. OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
    10. ...
    11. return "index";
    12. }
    13. }

    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
    1. @Bean
    2. public OAuth2AuthorizedClientManager authorizedClientManager(
    3. ClientRegistrationRepository clientRegistrationRepository,
    4. OAuth2AuthorizedClientRepository authorizedClientRepository) {
    5. OAuth2AuthorizedClientProvider authorizedClientProvider =
    6. OAuth2AuthorizedClientProviderBuilder.builder()
    7. .authorizationCode()
    8. .refreshToken()
    9. .clientCredentials()
    10. .password()
    11. .build();
    12. DefaultOAuth2AuthorizedClientManager authorizedClientManager =
    13. new DefaultOAuth2AuthorizedClientManager(
    14. clientRegistrationRepository, authorizedClientRepository);
    15. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
    16. return authorizedClientManager;
    17. }

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

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

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

    • Java
    1. @Bean
    2. public OAuth2AuthorizedClientManager authorizedClientManager(
    3. ClientRegistrationRepository clientRegistrationRepository,
    4. OAuth2AuthorizedClientRepository authorizedClientRepository) {
    5. OAuth2AuthorizedClientProvider authorizedClientProvider =
    6. OAuth2AuthorizedClientProviderBuilder.builder()
    7. .password()
    8. .refreshToken()
    9. .build();
    10. DefaultOAuth2AuthorizedClientManager authorizedClientManager =
    11. new DefaultOAuth2AuthorizedClientManager(
    12. clientRegistrationRepository, authorizedClientRepository);
    13. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
    14. // Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters,
    15. // map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
    16. authorizedClientManager.setContextAttributesMapper(contextAttributesMapper());
    17. return authorizedClientManager;
    18. }
    19. private Function<OAuth2AuthorizeRequest, Map<String, Object>> contextAttributesMapper() {
    20. return authorizeRequest -> {
    21. Map<String, Object> contextAttributes = Collections.emptyMap();
    22. HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
    23. String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
    24. String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD);
    25. if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
    26. contextAttributes = new HashMap<>();
    27. // `PasswordOAuth2AuthorizedClientProvider` requires both attributes
    28. contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
    29. contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
    30. }
    31. return contextAttributes;
    32. };
    33. }

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

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

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

    • Java
    1. @Bean
    2. public OAuth2AuthorizedClientManager authorizedClientManager(
    3. ClientRegistrationRepository clientRegistrationRepository,
    4. OAuth2AuthorizedClientService authorizedClientService) {
    5. OAuth2AuthorizedClientProvider authorizedClientProvider =
    6. OAuth2AuthorizedClientProviderBuilder.builder()
    7. .clientCredentials()
    8. .build();
    9. AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager =
    10. new AuthorizedClientServiceOAuth2AuthorizedClientManager(
    11. clientRegistrationRepository, authorizedClientService);
    12. authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
    13. return authorizedClientManager;
    14. }

  • 相关阅读:
    matlab新建数据字典及如何导入
    4核8G服务器选阿里云还是腾讯云?价格性能对比
    物联网平台中常用的一些Java工具类
    商业智能BI,助力企业数据文化建设
    开关电源测试方法分享:开关电源关机维持时间的测试步骤、测试标准
    图08 --- 网络的最大流
    【Go】单例模式与Once源码
    ApiJson简单使用
    python浏览器自动化环境搭建selenium
    gsap的简单用法
  • 原文地址:https://blog.csdn.net/leesinbad/article/details/133946786