# 高级配置

`HttpSecurity.oauth2Login()`提供了许多用于定制OAuth2.0登录的配置选项。主要配置选项被分组到它们的协议端点对应项中。

例如，`oauth2Login().authorizationEndpoint()`允许配置*授权端点*，而`oauth2Login().tokenEndpoint()`允许配置*令牌端点*。

下面的代码展示了一个示例：

例1.高级OAuth2登录配置

Java

```
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Login(oauth2 -> oauth2
			    .authorizationEndpoint(authorization -> authorization
			            ...
			    )
			    .redirectionEndpoint(redirection -> redirection
			            ...
			    )
			    .tokenEndpoint(token -> token
			            ...
			    )
			    .userInfoEndpoint(userInfo -> userInfo
			            ...
			    )
			);
	}
}
```

Kotlin

```
@EnableWebSecurity
class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Login {
                authorizationEndpoint {
                    ...
                }
                redirectionEndpoint {
                    ...
                }
                tokenEndpoint {
                    ...
                }
                userInfoEndpoint {
                    ...
                }
            }
        }
    }
}
```

`oauth2Login()`DSL的主要目标是与规范中定义的命名紧密地保持一致。

OAuth2.0授权框架将[协议端点](https://tools.ietf.org/html/rfc6749#section-3)定义如下：

授权过程使用两个授权服务器端点（HTTP资源）：

* 授权端点：由客户端使用，通过用户代理重定向从资源所有者处获得授权。

* 令牌端点：由客户端使用，用于将授权许可交换为访问令牌，通常与客户端身份验证一起使用。

以及一个客户端端点：

* 重定向端点：授权服务器用于通过资源所有者User-Agent向客户端返回包含授权凭据的响应。

OpenID Connect Core1.0规范将[用户信息端点](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo)定义如下：

UserInfo端点是一个受OAuth2.0保护的资源，它返回关于经过身份验证的最终用户的声明。为了获得所请求的关于最终用户的权利要求，客户端使用通过OpenID Connect身份验证获得的访问令牌向UserInfo端点发出请求。这些权利要求通常由一个JSON对象表示，该对象包含权利要求的名称-值对的集合。

以下代码显示了`oauth2Login()`DSL可用的完整配置选项：

例2. OAuth2登录配置选项

Java

```
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Login(oauth2 -> oauth2
			    .clientRegistrationRepository(this.clientRegistrationRepository())
			    .authorizedClientRepository(this.authorizedClientRepository())
			    .authorizedClientService(this.authorizedClientService())
			    .loginPage("/login")
			    .authorizationEndpoint(authorization -> authorization
			        .baseUri(this.authorizationRequestBaseUri())
			        .authorizationRequestRepository(this.authorizationRequestRepository())
			        .authorizationRequestResolver(this.authorizationRequestResolver())
			    )
			    .redirectionEndpoint(redirection -> redirection
			        .baseUri(this.authorizationResponseBaseUri())
			    )
			    .tokenEndpoint(token -> token
			        .accessTokenResponseClient(this.accessTokenResponseClient())
			    )
			    .userInfoEndpoint(userInfo -> userInfo
			        .userAuthoritiesMapper(this.userAuthoritiesMapper())
			        .userService(this.oauth2UserService())
			        .oidcUserService(this.oidcUserService())
			    )
			);
	}
}
```

Kotlin

```
@EnableWebSecurity
class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Login {
                clientRegistrationRepository = clientRegistrationRepository()
                authorizedClientRepository = authorizedClientRepository()
                authorizedClientService = authorizedClientService()
                loginPage = "/login"
                authorizationEndpoint {
                    baseUri = authorizationRequestBaseUri()
                    authorizationRequestRepository = authorizationRequestRepository()
                    authorizationRequestResolver = authorizationRequestResolver()
                }
                redirectionEndpoint {
                    baseUri = authorizationResponseBaseUri()
                }
                tokenEndpoint {
                    accessTokenResponseClient = accessTokenResponseClient()
                }
                userInfoEndpoint {
                    userAuthoritiesMapper = userAuthoritiesMapper()
                    userService = oauth2UserService()
                    oidcUserService = oidcUserService()
                }
            }
        }
    }
}
```

除了`oauth2Login()`DSL之外，还支持XML配置。

以下代码显示了[安全命名空间](../../appendix/namespace/http.html#nsa-oauth2-login)中可用的完整配置选项：

例3. OAuth2登录XML配置选项

```
<http>
	<oauth2-login client-registration-repository-ref="clientRegistrationRepository"
				  authorized-client-repository-ref="authorizedClientRepository"
				  authorized-client-service-ref="authorizedClientService"
				  authorization-request-repository-ref="authorizationRequestRepository"
				  authorization-request-resolver-ref="authorizationRequestResolver"
				  access-token-response-client-ref="accessTokenResponseClient"
				  user-authorities-mapper-ref="userAuthoritiesMapper"
				  user-service-ref="oauth2UserService"
				  oidc-user-service-ref="oidcUserService"
				  login-processing-url="/login/oauth2/code/*"
				  login-page="/login"
				  authentication-success-handler-ref="authenticationSuccessHandler"
				  authentication-failure-handler-ref="authenticationFailureHandler"
				  jwt-decoder-factory-ref="jwtDecoderFactory"/>
</http>
```

以下小节将详细介绍每种可用的配置选项：

* [OAuth2.0登录页面](#oauth2login-advanced-login-page)

* [重定向端点](#oauth2login-advanced-redirection-endpoint)

* [用户信息端点](#oauth2login-advanced-userinfo-endpoint)

* [ID令牌签名验证](#oauth2login-advanced-idtoken-verify)

* [OpenID Connect1.0注销](#oauth2login-advanced-oidc-logout)

## OAuth2.0登录页面

默认情况下，OAuth2.0登录页面是由`DefaultLoginPageGeneratingFilter`自动生成的。默认登录页面显示了每个配置的OAuth客户机，其`ClientRegistration.clientName`作为链接，该链接能够发起授权请求（或OAuth2.0登录）。

|   |为了使`DefaultLoginPageGeneratingFilter`显示用于配置的OAuth客户端的链接，已注册的`ClientRegistrationRepository`还需要实现`Iterable<ClientRegistration>`。<br/>参见`InMemoryClientRegistrationRepository`以供参考。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

每个OAuth客户端的链接目标默认为以下内容：

`OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/{registrationId}"`

下面的一行显示了一个示例：

```
<a href="/oauth2/authorization/google">Google</a>
```

若要覆盖默认的登录页面，请配置`oauth2Login().loginPage()`和（可选地）`oauth2Login().authorizationEndpoint().baseUri()`。

下面的清单展示了一个示例：

例4. OAuth2登录页面配置

Java

```
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Login(oauth2 -> oauth2
			    .loginPage("/login/oauth2")
			    ...
			    .authorizationEndpoint(authorization -> authorization
			        .baseUri("/login/oauth2/authorization")
			        ...
			    )
			);
	}
}
```

Kotlin

```
@EnableWebSecurity
class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Login {
                loginPage = "/login/oauth2"
                authorizationEndpoint {
                    baseUri = "/login/oauth2/authorization"
                }
            }
        }
    }
}
```

XML

```
<http>
	<oauth2-login login-page="/login/oauth2"
				  ...
    />
</http>
```

|   |你需要提供一个`@Controller`和一个`@RequestMapping("/login/oauth2")`，它能够呈现自定义登录页面。|
|---|---------------------------------------------------------------------------------------------------------------------------------|

|   |如前所述，配置`oauth2Login().authorizationEndpoint().baseUri()`是可选的。<br/>但是，如果你选择自定义它，请确保每个OAuth客户机的链接匹配`authorizationEndpoint().baseUri()`。<br/><br/>下面的一行显示了一个示例：<br/><br/>```<br/><a href="/login/oauth2/authorization/google">Google</a><br/>```|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

## 重定向端点

授权服务器使用重定向端点通过资源所有者User-Agent将授权响应（其中包含授权凭据）返回给客户端。

|   |OAuth2.0Login利用了授权代码授权。<br/>因此，授权凭据是授权代码。|
|---|------------------------------------------------------------------------------------------------------------------------------|

默认的授权响应`baseUri`（重定向端点）是`**/login/oauth2/code/***`，它在`OAuth2LoginAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI`中定义。

如果你想定制授权响应`baseUri`，请按照下面的示例配置它：

例5.重定向端点配置

Java

```
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Login(oauth2 -> oauth2
			    .redirectionEndpoint(redirection -> redirection
			        .baseUri("/login/oauth2/callback/*")
			        ...
			    )
			);
	}
}
```

Kotlin

```
@EnableWebSecurity
class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Login {
                redirectionEndpoint {
                    baseUri = "/login/oauth2/callback/*"
                }
            }
        }
    }
}
```

XML

```
<http>
	<oauth2-login login-processing-url="/login/oauth2/callback/*"
				  ...
    />
</http>
```

|   |你还需要确保`ClientRegistration.redirectUri`与自定义授权响应`baseUri`匹配。<br/><br/>下面的列表显示了一个示例：<br/><br/><br/><br/><br/>
```
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Login(oauth2 -> oauth2
			    .redirectionEndpoint(redirection -> redirection
			        .baseUri("/login/oauth2/callback/*")
			        ...
			    )
			);
	}
}
```r=“85”/>>>>><gt="73"/>|
|---| |

## 用户信息端点

UserInfo端点包括许多配置选项，如下文子部分所述：

* [映射用户权限](#oauth2login-advanced-map-authorities)

* [OAuth2.0用户服务](#oauth2login-advanced-oauth2-user-service)

* [OpenID Connect1.0用户服务](#oauth2login-advanced-oidc-user-service)

### 映射用户权限

在用户成功地使用OAuth2.0提供程序进行身份验证之后，`OAuth2User.getAuthorities()`（或`OidcUser.getAuthorities()`）可以被映射到一组新的`GrantedAuthority`实例，在完成身份验证时，该实例将被提供给`OAuth2AuthenticationToken`。

|   |`OAuth2AuthenticationToken.getAuthorities()`用于授权请求，例如在`hasRole('USER')`或`hasRole('ADMIN')`中。|
|---|----------------------------------------------------------------------------------------------------------------------------------|

在映射用户权限时，有两个选项可供选择：

* [使用grantedauthoritiesmapper ](#oauth2login-advanced-map-authorities-grantedauthoritiesmapper)

* [基于OAuth2UserService的授权策略](#oauth2login-advanced-map-authorities-oauth2userservice)

#### 使用grantedauthoritiesmapper

提供`GrantedAuthoritiesMapper`的实现，并将其配置为以下示例所示：

例6.授予权限映射器配置

Java

```
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Login(oauth2 -> oauth2
			    .userInfoEndpoint(userInfo -> userInfo
			        .userAuthoritiesMapper(this.userAuthoritiesMapper())
			        ...
			    )
			);
	}

	private GrantedAuthoritiesMapper userAuthoritiesMapper() {
		return (authorities) -> {
			Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

			authorities.forEach(authority -> {
				if (OidcUserAuthority.class.isInstance(authority)) {
					OidcUserAuthority oidcUserAuthority = (OidcUserAuthority)authority;

					OidcIdToken idToken = oidcUserAuthority.getIdToken();
					OidcUserInfo userInfo = oidcUserAuthority.getUserInfo();

					// Map the claims found in idToken and/or userInfo
					// to one or more GrantedAuthority's and add it to mappedAuthorities

				} else if (OAuth2UserAuthority.class.isInstance(authority)) {
					OAuth2UserAuthority oauth2UserAuthority = (OAuth2UserAuthority)authority;

					Map<String, Object> userAttributes = oauth2UserAuthority.getAttributes();

					// Map the attributes found in userAttributes
					// to one or more GrantedAuthority's and add it to mappedAuthorities

				}
			});

			return mappedAuthorities;
		};
	}
}
```

Kotlin

```
@EnableWebSecurity
class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Login {
                userInfoEndpoint {
                    userAuthoritiesMapper = userAuthoritiesMapper()
                }
            }
        }
    }

    private fun userAuthoritiesMapper(): GrantedAuthoritiesMapper = GrantedAuthoritiesMapper { authorities: Collection<GrantedAuthority> ->
        val mappedAuthorities = emptySet<GrantedAuthority>()

        authorities.forEach { authority ->
            if (authority is OidcUserAuthority) {
                val idToken = authority.idToken
                val userInfo = authority.userInfo
                // Map the claims found in idToken and/or userInfo
                // to one or more GrantedAuthority's and add it to mappedAuthorities
            } else if (authority is OAuth2UserAuthority) {
                val userAttributes = authority.attributes
                // Map the attributes found in userAttributes
                // to one or more GrantedAuthority's and add it to mappedAuthorities
            }
        }

        mappedAuthorities
    }
}
```

XML

```
<http>
	<oauth2-login user-authorities-mapper-ref="userAuthoritiesMapper"
				  ...
    />
</http>
```

或者，你可以注册一个`GrantedAuthoritiesMapper``@Bean`以使其自动应用于配置，如以下示例所示：

例7.授予权限映射器 Bean 配置

Java

```
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
		    .oauth2Login(withDefaults());
	}

	@Bean
	public GrantedAuthoritiesMapper userAuthoritiesMapper() {
		...
	}
}
```

Kotlin

```
@EnableWebSecurity
class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Login { }
        }
    }

    @Bean
    fun userAuthoritiesMapper(): GrantedAuthoritiesMapper {
        ...
    }
}
```

#### 基于OAuth2UserService的授权策略

与使用`GrantedAuthoritiesMapper`相比，这种策略是先进的，但是，它也更灵活，因为它允许你访问`OAuth2UserRequest`和`OAuth2User`（当使用OAuth2.0用户服务时）或`OidcUserRequest`和`OidcUser`（当使用OpenID Connect1.0用户服务时）。

`OAuth2UserRequest`（和`OidcUserRequest`）为你提供了对相关`OAuth2AccessToken`的访问，这在*委派者*需要从受保护的资源获取权限信息，然后才能为用户映射自定义权限的情况下非常有用。

下面的示例展示了如何使用OpenID Connect1.0UserService实现和配置基于委托的策略：

例8. OAuth2用户服务配置

Java

```
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Login(oauth2 -> oauth2
			    .userInfoEndpoint(userInfo -> userInfo
			        .oidcUserService(this.oidcUserService())
			        ...
			    )
			);
	}

	private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
		final OidcUserService delegate = new OidcUserService();

		return (userRequest) -> {
			// Delegate to the default implementation for loading a user
			OidcUser oidcUser = delegate.loadUser(userRequest);

			OAuth2AccessToken accessToken = userRequest.getAccessToken();
			Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

			// TODO
			// 1) Fetch the authority information from the protected resource using accessToken
			// 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities

			// 3) Create a copy of oidcUser but use the mappedAuthorities instead
			oidcUser = new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo());

			return oidcUser;
		};
	}
}
```

Kotlin

```
@EnableWebSecurity
class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Login {
                userInfoEndpoint {
                    oidcUserService = oidcUserService()
                }
            }
        }
    }

    @Bean
    fun oidcUserService(): OAuth2UserService<OidcUserRequest, OidcUser> {
        val delegate = OidcUserService()

        return OAuth2UserService { userRequest ->
            // Delegate to the default implementation for loading a user
            var oidcUser = delegate.loadUser(userRequest)

            val accessToken = userRequest.accessToken
            val mappedAuthorities = HashSet<GrantedAuthority>()

            // TODO
            // 1) Fetch the authority information from the protected resource using accessToken
            // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities
            // 3) Create a copy of oidcUser but use the mappedAuthorities instead
            oidcUser = DefaultOidcUser(mappedAuthorities, oidcUser.idToken, oidcUser.userInfo)

            oidcUser
        }
    }
}
```

XML

```
<http>
	<oauth2-login oidc-user-service-ref="oidcUserService"
				  ...
    />
</http>
```

### OAuth2.0用户服务

`DefaultOAuth2UserService`是支持标准OAuth2.0提供者的`OAuth2UserService`的实现。

|   |`OAuth2UserService`从userinfo端点获取最终用户（资源所有者）的用户属性（通过在授权流期间使用授予客户端的访问令牌），并以`OAuth2User`的形式返回`AuthenticatedPrincipal`。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

当在UserInfo端点请求用户属性时，`DefaultOAuth2UserService`使用`RestOperations`。

如果需要自定义用户信息请求的预处理，则可以提供带有自定义`DefaultOAuth2UserService.setRequestEntityConverter()`的`Converter<OAuth2UserRequest, RequestEntity<?>>`。默认实现`OAuth2UserRequestEntityConverter`构建了用户信息请求的`RequestEntity`表示，该表示默认情况下在`Authorization`头中设置`OAuth2AccessToken`。

在另一端，如果需要自定义用户信息响应的后处理，则需要为`DefaultOAuth2UserService.setRestOperations()`提供自定义配置的`RestOperations`。默认的`RestOperations`配置如下：

```
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
```

`OAuth2ErrorResponseErrorHandler`是可以处理OAuth2.0错误（400BAD请求）的`ResponseErrorHandler`。它使用`OAuth2ErrorHttpMessageConverter`将OAuth2.0错误参数转换为`OAuth2Error`。

无论你是自定义`DefaultOAuth2UserService`还是提供你自己的`OAuth2UserService`实现，你都需要对其进行配置，如以下示例所示：

Java

```
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Login(oauth2 -> oauth2
			    .userInfoEndpoint(userInfo -> userInfo
			        .userService(this.oauth2UserService())
			        ...
			    )
			);
	}

	private OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {
		...
	}
}
```

Kotlin

```
@EnableWebSecurity
class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Login {
                userInfoEndpoint {
                    userService = oauth2UserService()
                    // ...
                }
            }
        }
    }

    private fun oauth2UserService(): OAuth2UserService<OAuth2UserRequest, OAuth2User> {
        // ...
    }
}
```

### OpenID Connect1.0用户服务

`OidcUserService`是支持OpenID Connect1.0Provider的`OAuth2UserService`的实现。

当在UserInfo端点请求用户属性时，`OidcUserService`利用了`DefaultOAuth2UserService`。

如果需要自定义用户信息请求的预处理和/或用户信息响应的后处理，则需要为`OidcUserService.setOauth2UserService()`提供自定义配置的`DefaultOAuth2UserService`。

无论你是定制`OidcUserService`还是为OpenID Connect1.0Provider提供你自己的`OAuth2UserService`实现，你都需要对其进行配置，如以下示例所示：

Java

```
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Login(oauth2 -> oauth2
				.userInfoEndpoint(userInfo -> userInfo
				    .oidcUserService(this.oidcUserService())
				    ...
			    )
			);
	}

	private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
		...
	}
}
```

Kotlin

```
@EnableWebSecurity
class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Login {
                userInfoEndpoint {
                    oidcUserService = oidcUserService()
                    // ...
                }
            }
        }
    }

    private fun oidcUserService(): OAuth2UserService<OidcUserRequest, OidcUser> {
        // ...
    }
}
```

## ID令牌签名验证

OpenID Connect1.0身份验证引入了[ID Token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken)，这是一种安全令牌，其中包含关于客户端使用授权服务器对最终用户进行身份验证的声明。

ID令牌表示为[JSON网络令牌](https://tools.ietf.org/html/rfc7519)，并且必须使用[JSON网页签名](https://tools.ietf.org/html/rfc7515)进行签名。

`OidcIdTokenDecoderFactory`提供了用于`JwtDecoder`签名验证的`OidcIdToken`。默认的算法是`RS256`，但在客户端注册期间分配时可能会有所不同。对于这些情况，可以将解析器配置为返回为特定客户端分配的预期JWS算法。

JWS算法解析器是一个`Function`，它接受一个`ClientRegistration`，并为客户机返回预期的`JwsAlgorithm`，例如。`SignatureAlgorithm.RS256`或`MacAlgorithm.HS256`

下面的代码显示了如何将`OidcIdTokenDecoderFactory``@Bean`配置为所有`MacAlgorithm.HS256`的默认`MacAlgorithm.HS256`:

Java

```
@Bean
public JwtDecoderFactory<ClientRegistration> idTokenDecoderFactory() {
	OidcIdTokenDecoderFactory idTokenDecoderFactory = new OidcIdTokenDecoderFactory();
	idTokenDecoderFactory.setJwsAlgorithmResolver(clientRegistration -> MacAlgorithm.HS256);
	return idTokenDecoderFactory;
}
```

Kotlin

```
@Bean
fun idTokenDecoderFactory(): JwtDecoderFactory<ClientRegistration?> {
    val idTokenDecoderFactory = OidcIdTokenDecoderFactory()
    idTokenDecoderFactory.setJwsAlgorithmResolver { MacAlgorithm.HS256 }
    return idTokenDecoderFactory
}
```

|   |对于基于MAC的算法，如`HS256`、`HS384`或`HS512`，对应于`client-secret`的`client-secret`被用作签名验证的对称密钥。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |如果一个以上的`ClientRegistration`被配置为用于OpenID Connect1.0身份验证，则JWS算法解析器可以对提供的`ClientRegistration`进行评估，以确定返回哪个算法。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

## OpenID Connect1.0注销

OpenID Connect会话Management1.0允许使用客户端在提供商处注销最终用户。可用的策略之一是[RP启动的注销](https://openid.net/specs/openid-connect-session-1_0.html#RPLogout)。

如果OpenID提供程序同时支持会话管理和[Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html)，则客户端可以从OpenID提供程序的`end_session_endpoint``URL`中获得[发现元数据](https://openid.net/specs/openid-connect-session-1_0.html#OPMetadata)。这可以通过配置`ClientRegistration`和`issuer-uri`来实现，如下例所示：

```
spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
            ...
        provider:
          okta:
            issuer-uri: https://dev-1234.oktapreview.com
```

…和`OidcClientInitiatedLogoutSuccessHandler`，它实现RP-initedlogout，可以配置如下：

Java

```
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private ClientRegistrationRepository clientRegistrationRepository;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.authorizeHttpRequests(authorize -> authorize
				.anyRequest().authenticated()
			)
			.oauth2Login(withDefaults())
			.logout(logout -> logout
				.logoutSuccessHandler(oidcLogoutSuccessHandler())
			);
	}

	private LogoutSuccessHandler oidcLogoutSuccessHandler() {
		OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler =
				new OidcClientInitiatedLogoutSuccessHandler(this.clientRegistrationRepository);

		// Sets the location that the End-User's User Agent will be redirected to
		// after the logout has been performed at the Provider
		oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}");

		return oidcLogoutSuccessHandler;
	}
}
```

Kotlin

```
@EnableWebSecurity
class OAuth2LoginSecurityConfig : WebSecurityConfigurerAdapter() {
    @Autowired
    private lateinit var clientRegistrationRepository: ClientRegistrationRepository

    override fun configure(http: HttpSecurity) {
        http {
            authorizeRequests {
                authorize(anyRequest, authenticated)
            }
            oauth2Login { }
            logout {
                logoutSuccessHandler = oidcLogoutSuccessHandler()
            }
        }
    }

    private fun oidcLogoutSuccessHandler(): LogoutSuccessHandler {
        val oidcLogoutSuccessHandler = OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository)

        // Sets the location that the End-User's User Agent will be redirected to
        // after the logout has been performed at the Provider
        oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}")
        return oidcLogoutSuccessHandler
    }
}
```

|   |`OidcClientInitiatedLogoutSuccessHandler`支持`{baseUrl}`占位符。<br/>如果使用的话，应用程序的基本URL，如`[https://app.example.org](https://app.example.org)`，将在请求时替换它。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

[核心配置](core.html)[OAuth2客户端](../client/index.html)