在上一篇我们分析了如何把请求转换成 Authentication 认证信息对象。接下来,我们将分析ReactiveAuthenticationManager如何来认证授权,它内部的工作流程是如何的。
初始化ReativeAuthenticationManager
在 ServerHttpSecurity 类的内部类 OAuth2LoginSpec 的 configure() 方法内,OAuth2LoginAuthenticationWebFilter 初始化了 ReativeAuthenticationManager。如果我们没有指定 ReativeAuthenticationManager,就创建默认的;否则使用指定的。ReativeAuthenticationManager会依赖两个类:ReactiveOAuth2AccessTokenResponseClient(用来获取Access Token)、ReactiveOAuth2UserService(用来获取第三方用户信息的)。源码如下所示:
private ReactiveAuthenticationManager getAuthenticationManager() {
if (this.authenticationManager == null) {
this.authenticationManager = this.createDefault();
}
return this.authenticationManager;
}
private ReactiveAuthenticationManager createDefault() {
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> client = this.getAccessTokenResponseClient();
OAuth2LoginReactiveAuthenticationManager oauth2Manager = new OAuth2LoginReactiveAuthenticationManager(client, this.getOauth2UserService());
GrantedAuthoritiesMapper authoritiesMapper = (GrantedAuthoritiesMapper)ServerHttpSecurity.this.getBeanOrNull(GrantedAuthoritiesMapper.class);
if (authoritiesMapper != null) {
oauth2Manager.setAuthoritiesMapper(authoritiesMapper);
}
boolean oidcAuthenticationProviderEnabled = ClassUtils.isPresent("org.springframework.security.oauth2.jwt.JwtDecoder", this.getClass().getClassLoader());
if (!oidcAuthenticationProviderEnabled) {
return oauth2Manager;
} else {
OidcAuthorizationCodeReactiveAuthenticationManager oidc = new OidcAuthorizationCodeReactiveAuthenticationManager(client, this.getOidcUserService());
ResolvableType type = ResolvableType.forClassWithGenerics(ReactiveJwtDecoderFactory.class, new Class[]{
ClientRegistration.class});
ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory = (ReactiveJwtDecoderFactory)ServerHttpSecurity.this.getBeanOrNull(type);
if (jwtDecoderFactory != null) {
oidc.setJwtDecoderFactory(jwtDecoderFactory);
}
if (authoritiesMapper != null) {
oidc.setAuthoritiesMapper(authoritiesMapper);
}
// 创建一组认证管理器,认证失败则由下一个进行认证;认证成功直接返回
return new DelegatingReactiveAuthenticationManager(new ReactiveAuthenticationManager[]{
oidc, oauth2Manager});
}
}
初始化ReactiveOAuth2AccessTokenResponseClient
在初始化 ReactiveOAuth2AccessTokenResponseClient时,首先会从Spring的容器内查找是否有ReactiveOAuth2AccessTokenResponseClient 的实例,如果有,则使用找到的实例;否则,创建默认类 WebClientReactiveAuthorizationCodeTokenResponseClient。源码如下所示:
private ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> getAccessTokenResponseClient() {
ResolvableType type = ResolvableType.forClassWithGenerics(ReactiveOAuth2AccessTokenResponseClient.class, new Class[]{
OAuth2AuthorizationCodeGrantRequest.