Spring Security 实战干货:OAuth2授权回调的核心认证流程
1. 前言
我们在上一篇Spring Security 实战干货:OAuth2授权回调的处理机制对OAuth2服务端调用客户端回调的流程进行了图解, 今天我们来深入了解OAuth2在回调中进行认证细节。
2. AuthenticationManager
当Spring Security拦截到回调接口后会封装一个OAuth2LoginAuthenticationToken交给AuthenticationManager进行认证。在之前Spring Security 实战干货:理解AuthenticationManager一文中我们正好对AuthenticationManager的机制有详细的讲解,所以要快速理解本文应该去看看这一篇。
其中登录认证凭据封装为UsernamePasswordAuthenticationToken 然后根据Token的类型找到对应的AuthenticationProvider进行认证。

3. OAuth2对应的AuthenticationProvider
那么OAuth2登录有异曲同工之妙,我们需要找到OAuth2LoginAuthenticationToken对应的AuthenticationProvider。这里找到了两个:
OAuth2LoginAuthenticationProviderOidcAuthorizationCodeAuthenticationProvider
这两个各自对应的场景是什么呢,OAuth2LoginAuthenticationToken中有以下片段:
if (loginAuthenticationToken.getAuthorizationExchange()
.getAuthorizationRequest().getScopes().contains("openid")) {
// This is an OpenID Connect Authentication Request so return null
// and let OidcAuthorizationCodeAuthenticationProvider handle it instead
return null;
}
意思是说scopes中如果包含了openid就直接返回null,不会被OAuth2LoginAuthenticationToken处理,而OidcAuthorizationCodeAuthenticationProvider中正好相反。 根据以往文章的脉络OAuth2LoginAuthenticationProvider就是我们需要的。
有兴趣可取了解基于OIDC的OAuth2认证。
4. OAuth2LoginAuthenticationProvider
OAuth2LoginAuthenticationProvider实现了授权回调的认证过程:

从上图中我们可以看出具体认证由OAuth2AuthorizationCodeAuthenticationProvider来负责,认证通过后会去获取用户的信息并封装为OAuth2User,最终生成授权成功的OAuth2LoginAuthenticationToken。
基于篇幅的原因,下一篇我们会分析OAuth2AuthorizationCodeAuthenticationProvider的处理机制。
评论系统未开启,无法评论!