此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Security 6.5.3! |
核心接口和类
本节介绍 Spring Security 提供的 OAuth2 核心接口和类。
客户注册
ClientRegistration
是在 OAuth 2.0 或 OpenID Connect 1.0 提供程序中注册的客户端的表示形式。
一个ClientRegistration
对象包含信息,例如客户端 ID、客户端密码、授权授予类型、重定向 URI、范围、授权 URI、Tokens 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)
}
}
public static final class ClientSettings {
private boolean requireProofKey; (17)
}
}
1 | registrationId :唯一标识ClientRegistration . |
2 | clientId :客户端标识符。 |
3 | clientSecret :客户端密钥。 |
4 | clientAuthenticationMethod :用于向提供商验证客户端的方法。支持的值为 client_secret_basic、client_secret_post、private_key_jwt、client_secret_jwt 和 none(公共客户端)。 |
5 | authorizationGrantType :OAuth 2.0 授权框架定义了四种授权授权类型。支持的值包括authorization_code ,client_credentials 以及延期授权类型urn:ietf:params:oauth:grant-type:jwt-bearer . |
6 | redirectUri :客户端注册的重定向 URI,授权服务器在最终用户对客户端进行身份验证并授权访问后将最终用户的用户代理重定向到最终用户对客户端的访问。 |
7 | scopes :客户端在授权请求流期间请求的范围,例如 openid、电子邮件或配置文件。 |
8 | clientName :用于客户端的描述性名称。该名称可能在某些情况下使用,例如在自动生成的登录页面中显示客户端名称时。 |
9 | authorizationUri :授权服务器的授权终结点 URI。 |
10 | tokenUri :授权服务器的Tokens端点 URI。 |
11 | jwkSetUri :用于从授权服务器检索 JSON Web 密钥 (JWK) 集的 URI,其中包含用于验证 ID Tokens的 JSON Web 签名 (JWS) 和(可选)UserInfo 响应的加密密钥。 |
12 | issuerUri :返回 OpenID Connect 1.0 提供程序或 OAuth 2.0 授权服务器的颁发者标识符 URI。 |
13 | configurationMetadata :OpenID 提供程序配置信息。仅当 Spring Boot 属性时,此信息才可用spring.security.oauth2.client.provider.[providerId].issuerUri 已配置。 |
14 | (userInfoEndpoint)uri :用于访问经过身份验证的最终用户的声明和属性的 UserInfo 终结点 URI。 |
15 | (userInfoEndpoint)authenticationMethod :将访问Tokens发送到 UserInfo 终结点时使用的身份验证方法。支持的值包括 header、form 和 query。 |
16 | userNameAttributeName :引用最终用户的名称或标识符的 UserInfo 响应中返回的属性的名称。 |
17 | requireProofKey :如果true 或者如果authorizationGrantType 是none ,则默认启用 PKCE。 |
ClientRegistrations
提供了配置ClientRegistration
这样,如下所示:
-
Java
-
Kotlin
ClientRegistration clientRegistration =
ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build();
val 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 提供程序的配置端点。
客户端注册存储库
这ClientRegistrationRepository
用作 OAuth 2.0 / OpenID Connect 1.0 的存储库ClientRegistration
(s)。
客户端注册信息最终由关联的授权服务器存储和拥有。此存储库提供了检索主客户端注册信息子集的功能,这些信息存储在授权服务器中。 |
Spring Boot 自动配置绑定了spring.security.oauth2.client.registration.[registrationId]
设置为ClientRegistration
然后组成每个ClientRegistration
实例ClientRegistrationRepository
.
默认实现 |
自动配置还注册ClientRegistrationRepository
作为@Bean
在ApplicationContext
以便它可以在应用程序需要时用于依赖项注入。
以下列表显示了一个示例:
-
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";
}
}
OAuth2授权客户端
OAuth2AuthorizedClient
是授权客户端的表示形式。当最终用户(资源所有者)已向客户端授予访问其受保护资源的授权时,客户端被视为已授权。
OAuth2AuthorizedClient
用于关联OAuth2AccessToken
(和可选的OAuth2RefreshToken
) 设置为ClientRegistration
(客户端)和资源所有者,他们是Principal
授予授权的最终用户。
OAuth2AuthorizedClientRepository 和 OAuth2AuthorizedClientService
OAuth2AuthorizedClientRepository
负责持久化OAuth2AuthorizedClient
(s) 在 Web 请求之间,而OAuth2AuthorizedClientService
就是要管理OAuth2AuthorizedClient
(s) 在应用层面。
从开发人员的角度来看,OAuth2AuthorizedClientRepository
或OAuth2AuthorizedClientService
提供查找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 自动配置注册一个 |
默认实现OAuth2AuthorizedClientService
是InMemoryOAuth2AuthorizedClientService
,存储OAuth2AuthorizedClient
内存中的对象。
或者,您可以配置 JDBC 实现JdbcOAuth2AuthorizedClientService
坚持OAuth2AuthorizedClient
数据库中的实例。
|
OAuth2AuthorizedClientManager 和 OAuth2AuthorizedClientProvider
这OAuth2AuthorizedClientManager
负责整体管理OAuth2AuthorizedClient
(s)。
主要职责包括:
-
授权(或重新授权)OAuth 2.0 客户端,方法是使用
OAuth2AuthorizedClientProvider
. -
委托
OAuth2AuthorizedClient
,通常通过使用OAuth2AuthorizedClientService
或OAuth2AuthorizedClientRepository
. -
委托给
OAuth2AuthorizationSuccessHandler
当 OAuth 2.0 客户端已成功授权(或重新授权)时。 -
委托给
OAuth2AuthorizationFailureHandler
当 OAuth 2.0 客户端无法授权(或重新授权)时。
一OAuth2AuthorizedClientProvider
实现授权(或重新授权)OAuth 2.0 客户端的策略。
实现通常实现授权授予类型,例如authorization_code
,client_credentials
,等。
默认实现OAuth2AuthorizedClientManager
是DefaultOAuth2AuthorizedClientManager
,它与OAuth2AuthorizedClientProvider
可能支持使用基于委派的复合的多种授权授予类型。
您可以使用OAuth2AuthorizedClientProviderBuilder
以配置和构建基于委派的复合。
以下代码显示了如何配置和构建OAuth2AuthorizedClientProvider
复合材料,为authorization_code
,refresh_token
和client_credentials
授权授权类型:
-
Java
-
Kotlin
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.clientCredentials()
.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()
.build()
val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository)
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
return authorizedClientManager
}
授权尝试成功后,DefaultOAuth2AuthorizedClientManager
委托到OAuth2AuthorizationSuccessHandler
,它(默认情况下)保存OAuth2AuthorizedClient
通过OAuth2AuthorizedClientRepository
.
如果重新授权失败(例如,刷新Tokens不再有效),则之前保存的OAuth2AuthorizedClient
从OAuth2AuthorizedClientRepository
通过RemoveAuthorizedClientOAuth2AuthorizationFailureHandler
.
您可以通过以下方式自定义默认行为setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler)
和setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler)
.
这DefaultOAuth2AuthorizedClientManager
还与contextAttributesMapper
类型Function<OAuth2AuthorizeRequest, Map<String, Object>>
,负责从OAuth2AuthorizeRequest
设置为Map
要与OAuth2AuthorizationContext
.
当您需要提供OAuth2AuthorizedClientProvider
具有必需(支持)属性。
以下代码显示了contextAttributesMapper
:
-
Java
-
Kotlin
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager =
new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Assuming the attributes 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 param1 = servletRequest.getParameter("param1");
String param2 = servletRequest.getParameter("param2");
if (StringUtils.hasText(param1) && StringUtils.hasText(param2)) {
contextAttributes = new HashMap<>();
contextAttributes.put("param1", param1);
contextAttributes.put("param2", param2);
}
return contextAttributes;
};
}
@Bean
fun authorizedClientManager(
clientRegistrationRepository: ClientRegistrationRepository,
authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.build()
val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository)
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
// Assuming the attributes 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 param1: String = servletRequest.getParameter("param1")
val param2: String = servletRequest.getParameter("param2")
if (StringUtils.hasText(param1) && StringUtils.hasText(param2)) {
contextAttributes = hashMapOf()
contextAttributes["param1"] = param1
contextAttributes["param2"] = param2
}
contextAttributes
}
}
这DefaultOAuth2AuthorizedClientManager
旨在在HttpServletRequest
.
在室外作时HttpServletRequest
上下文, 使用AuthorizedClientServiceOAuth2AuthorizedClientManager
相反。
服务应用程序是何时使用AuthorizedClientServiceOAuth2AuthorizedClientManager
.
服务应用程序通常在后台运行,无需任何用户交互,并且通常在系统级帐户而不是用户帐户下运行。
配置了client_credentials
授权类型可以被视为一种服务申请类型。
以下代码显示了如何配置AuthorizedClientServiceOAuth2AuthorizedClientManager
为client_credentials
赠款类型:
-
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
}