SpringBoot OAuth2 Client的授权核心由两个过滤器来实现:
OAuth2AuthorizationRequestRedirectWebFilter
OAuth2LoginAuthenticationWebFilter
OAuth2LoginAuthenticationWebFilter过滤器就是今天主要分析的主角。
概览
OAuth2LoginAuthenticationWebFilter过滤器依赖很多类:
- ReactiveAuthticationManager:获取Access Token、获取用户信息
- ServerOAuth2AuthorizedClientRepository
- ServerWebExchangeMatcher:用来匹配请求路径并拦截处理
- ServerAuthenticationSuccessHandler:授权成功后回调处理
- ServerAuthenticationFailureHandler:授权失败后回调处理
实现了如下功能:
- 授权码换取 AccessToken
- AccessToken换取用户信息(昵称、邮箱等等)
以下思维导图主要描述OAuth2LoginAuthenticatioinWebFilter依赖的类,方便我们能够对其清晰直观的了解。
核心源码分析
OAuth2LoginAuthticationWebFilter过滤器继承了 AuthenticationWebFilter 。所以其主要功能都是在父类 AuthenticationWebFilter 中完成。AuthenticationWebFilter 主要负责匹配请求路径并拦截处理、开始认证、认证成功后回调、失败后回调。源码如下所示。
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
// 由ServerWebExchangeMatcher匹配要拦截的请求路径
return this.requiresAuthenticationMatcher.matches(exchange).filter((matchResult) ->