核心接口和类

本节介绍 Spring Security 提供的 OAuth2 核心接口和类。

ClientRegistration

ClientRegistration 是在 OAuth 2.0 或 OpenID Connect 1.0 Provider 注册的客户端的表示。

ClientRegistration 对象包含客户端 ID、客户端 Secret、授权许可类型、重定向 URI、作用域 (scope)、授权 URI、令牌 URI 等信息。

ClientRegistration 及其属性定义如下:

public final class ClientRegistration {
	private String registrationId;	(1)
	private String clientId;	(2)
	private String clientSecret;	(3)
	private ClientAuthenticationMethod clientAuthenticationMethod;	(4)
	private AuthorizationGrantType authorizationGrantType;	(5)
	private String redirectUri;	(6)
	private Set<String> scopes;	(7)
	private ProviderDetails providerDetails;
	private String clientName;	(8)

	public class ProviderDetails {
		private String authorizationUri;	(9)
		private String tokenUri;	(10)
		private UserInfoEndpoint userInfoEndpoint;
		private String jwkSetUri;	(11)
		private String issuerUri;	(12)
        private Map<String, Object> configurationMetadata;  (13)

		public class UserInfoEndpoint {
			private String uri;	(14)
            private AuthenticationMethod authenticationMethod;  (15)
			private String userNameAttributeName;	(16)

		}
	}
}
1 registrationId:唯一标识此 ClientRegistration 的 ID。
2 clientId:客户端标识符。
3 clientSecret:客户端 Secret。
4 clientAuthenticationMethod:用于向 Provider 认证客户端的方法。支持的值包括 client_secret_basicclient_secret_postprivate_key_jwtclient_secret_jwtnone (公共客户端)
5 authorizationGrantType:OAuth 2.0 授权框架定义了四种 授权许可(Authorization Grant) 类型。支持的值包括 authorization_codeclient_credentialspassword,以及扩展许可类型 urn:ietf:params:oauth:grant-type:jwt-bearer
6 redirectUri:客户端注册的重定向 URI,在终端用户完成认证并授权客户端访问后,授权服务器(Authorization Server) 会将终端用户的 user-agent 重定向到此 URI。
7 scopes:客户端在授权请求流程中请求的作用域(scope),例如 openid、email 或 profile。
8 clientName:用于客户端的描述性名称。此名称可在某些场景下使用,例如在自动生成的登录页面中显示客户端名称。
9 authorizationUri:授权服务器的授权端点(Authorization Endpoint)URI。
10 tokenUri:授权服务器的令牌端点(Token Endpoint)URI。
11 jwkSetUri:用于从授权服务器检索 JSON Web Key (JWK) Set 的 URI,其中包含用于验证 ID Token 和(可选地)UserInfo 响应的 JSON Web Signature (JWS) 的加密密钥。
12 issuerUri:返回 OpenID Connect 1.0 provider 或 OAuth 2.0 授权服务器的颁发者标识符 URI。
13 configurationMetadataOpenID Provider 配置信息。此信息仅在配置了 Spring Boot 属性 spring.security.oauth2.client.provider.[providerId].issuerUri 时可用。
14 (userInfoEndpoint)uri:用于访问已认证终端用户的声明(claims)和属性的 UserInfo 端点 URI。
15 (userInfoEndpoint)authenticationMethod:将访问令牌发送到 UserInfo 端点时使用的认证方法。支持的值包括 headerformquery
16 userNameAttributeName:UserInfo 响应中返回的属性名称,该属性引用终端用户的名称或标识符。

您可以使用 OpenID Connect Provider 的配置端点(Configuration endpoint)发现或授权服务器的元数据端点(Metadata endpoint)发现来初步配置 ClientRegistration

ClientRegistrations 提供方便的方法来以这种方式配置 ClientRegistration,如下所示:

  • Java

  • Kotlin

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

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

ClientRegistrationRepository

ClientRegistrationRepository 用作 OAuth 2.0 / OpenID Connect 1.0 ClientRegistration 的存储库。

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

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

ClientRegistrationRepository 的默认实现是 InMemoryClientRegistrationRepository

自动配置还将 ClientRegistrationRepository 注册为 ApplicationContext 中的 @Bean,以便在应用程序需要时可用于依赖注入。

以下清单显示了一个示例:

  • Java

  • Kotlin

@Controller
public class OAuth2ClientController {

	@Autowired
	private ClientRegistrationRepository clientRegistrationRepository;

	@GetMapping("/")
	public String index() {
		ClientRegistration oktaRegistration =
			this.clientRegistrationRepository.findByRegistrationId("okta");

		...

		return "index";
	}
}
@Controller
class OAuth2ClientController {

    @Autowired
    private lateinit var clientRegistrationRepository: ClientRegistrationRepository

    @GetMapping("/")
    fun index(): String {
        val oktaRegistration =
                this.clientRegistrationRepository.findByRegistrationId("okta")

        //...

        return "index";
    }
}

OAuth2AuthorizedClient

OAuth2AuthorizedClient 是授权客户端(Authorized Client)的表示。当终端用户(资源所有者 Resource Owner)授予客户端访问其受保护资源的授权时,该客户端被认为是授权的(authorized)。

OAuth2AuthorizedClient 的作用是将 OAuth2AccessToken(以及可选的 OAuth2RefreshToken)与 ClientRegistration(客户端)和资源所有者(即授予授权的 Principal 终端用户)关联起来。

OAuth2AuthorizedClientRepository 和 OAuth2AuthorizedClientService

OAuth2AuthorizedClientRepository 负责在 Web 请求之间持久化 OAuth2AuthorizedClient,而 OAuth2AuthorizedClientService 的主要作用是在应用程序级别管理 OAuth2AuthorizedClient

从开发人员的角度来看,OAuth2AuthorizedClientRepositoryOAuth2AuthorizedClientService 提供了查找与客户端关联的 OAuth2AccessToken 的能力,以便可以使用它发起受保护的资源请求。

以下清单显示了一个示例:

  • Java

  • Kotlin

@Controller
public class OAuth2ClientController {

    @Autowired
    private OAuth2AuthorizedClientService authorizedClientService;

    @GetMapping("/")
    public String index(Authentication authentication) {
        OAuth2AuthorizedClient authorizedClient =
            this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName());

        OAuth2AccessToken accessToken = authorizedClient.getAccessToken();

        ...

        return "index";
    }
}
@Controller
class OAuth2ClientController {

    @Autowired
    private lateinit var authorizedClientService: OAuth2AuthorizedClientService

    @GetMapping("/")
    fun index(authentication: Authentication): String {
        val authorizedClient: OAuth2AuthorizedClient =
            this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName());
        val accessToken = authorizedClient.accessToken

        ...

        return "index";
    }
}

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

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

或者,您可以配置 JDBC 实现 JdbcOAuth2AuthorizedClientServiceOAuth2AuthorizedClient 实例持久化到数据库中。

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

OAuth2AuthorizedClientManager 和 OAuth2AuthorizedClientProvider

OAuth2AuthorizedClientManager 负责 OAuth2AuthorizedClient 的整体管理。

主要职责包括:

  • 使用 OAuth2AuthorizedClientProvider 对 OAuth 2.0 客户端进行授权(或重新授权)。

  • 委派 OAuth2AuthorizedClient 的持久化,通常通过使用 OAuth2AuthorizedClientServiceOAuth2AuthorizedClientRepository

  • 当 OAuth 2.0 客户端成功授权(或重新授权)时,委派给 OAuth2AuthorizationSuccessHandler 处理。

  • 当 OAuth 2.0 客户端授权(或重新授权)失败时,委派给 OAuth2AuthorizationFailureHandler 处理。

OAuth2AuthorizedClientProvider 实现授权(或重新授权)OAuth 2.0 客户端的策略。实现通常实现一种授权许可类型,例如 authorization_codeclient_credentials 等。

OAuth2AuthorizedClientManager 的默认实现是 DefaultOAuth2AuthorizedClientManager,它与一个 OAuth2AuthorizedClientProvider 相关联,后者可能使用基于委托的组合模式支持多种授权许可类型。您可以使用 OAuth2AuthorizedClientProviderBuilder 配置和构建基于委托的组合。

以下代码示例演示了如何配置和构建一个支持 authorization_coderefresh_tokenclient_credentialspassword 授权许可类型的 OAuth2AuthorizedClientProvider 组合:

  • Java

  • Kotlin

@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;
}
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .authorizationCode()
            .refreshToken()
            .clientCredentials()
            .password()
            .build()
    val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}

当授权尝试成功时,DefaultOAuth2AuthorizedClientManager 将委派给 OAuth2AuthorizationSuccessHandler,后者(默认情况下)通过 OAuth2AuthorizedClientRepository 保存 OAuth2AuthorizedClient。如果重新授权失败(例如,刷新令牌不再有效),则之前保存的 OAuth2AuthorizedClient 将通过 RemoveAuthorizedClientOAuth2AuthorizationFailureHandlerOAuth2AuthorizedClientRepository 中移除。您可以通过 setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler)setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler) 来自定义默认行为。

DefaultOAuth2AuthorizedClientManager 还关联了一个类型为 Function<OAuth2AuthorizeRequest, Map<String, Object>>contextAttributesMapper,它负责将属性从 OAuth2AuthorizeRequest 映射到一个属性 Map,以便与 OAuth2AuthorizationContext 关联。当您需要向 OAuth2AuthorizedClientProvider 提供必需(支持)的属性时,这会非常有用,例如 PasswordOAuth2AuthorizedClientProvider 要求资源所有者的 usernamepasswordOAuth2AuthorizationContext.getAttributes() 中可用。

以下代码示例展示了 contextAttributesMapper 的用法:

  • Java

  • Kotlin

@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 attributes
			contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
			contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
		}
		return contextAttributes;
	};
}
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .password()
            .refreshToken()
            .build()
    val authorizedClientManager = 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 fun contextAttributesMapper(): Function<OAuth2AuthorizeRequest, MutableMap<String, Any>> {
    return Function { authorizeRequest ->
        var contextAttributes: MutableMap<String, Any> = mutableMapOf()
        val servletRequest: HttpServletRequest = authorizeRequest.getAttribute(HttpServletRequest::class.java.name)
        val username: String = servletRequest.getParameter(OAuth2ParameterNames.USERNAME)
        val password: String = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD)
        if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
            contextAttributes = hashMapOf()

            // `PasswordOAuth2AuthorizedClientProvider` requires both attributes
            contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username
            contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password
        }
        contextAttributes
    }
}

DefaultOAuth2AuthorizedClientManager 设计用于在 HttpServletRequest 的上下文中使用。当在 HttpServletRequest 上下文之外操作时,请改用 AuthorizedClientServiceOAuth2AuthorizedClientManager

服务应用程序是使用 AuthorizedClientServiceOAuth2AuthorizedClientManager 的常见用例。服务应用程序通常在后台运行,无需任何用户交互,并且通常在系统级账户下运行,而非用户账户。配置了 client_credentials 许可类型的 OAuth 2.0 客户端可以被视为一种服务应用程序。

以下代码示例演示了如何配置支持 client_credentials 许可类型的 AuthorizedClientServiceOAuth2AuthorizedClientManager

  • Java

  • Kotlin

@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;
}
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientService: OAuth2AuthorizedClientService): OAuth2AuthorizedClientManager {
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .clientCredentials()
            .build()
    val authorizedClientManager = AuthorizedClientServiceOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientService)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}