Spring Security 實(shí)戰(zhàn)干貨:OAuth2授權(quán)回調(diào)的核心認(rèn)證流程
1. 前言
我們?cè)谏弦黄?Spring Security 實(shí)戰(zhàn)干貨:OAuth2 授權(quán)回調(diào)的處理機(jī)制 對(duì) OAuth2 服務(wù)端調(diào)用客戶端回調(diào)的流程進(jìn)行了圖解, 今天我們來(lái)深入了解 OAuth2 在回調(diào)中進(jìn)行認(rèn)證細(xì)節(jié)。
2. AuthenticationManager
當(dāng) Spring Security 攔截到回調(diào)接口后會(huì)封裝一個(gè)OAuth2LoginAuthenticationToken交給AuthenticationManager進(jìn)行認(rèn)證。在之前 Spring Security 實(shí)戰(zhàn)干貨:理解 AuthenticationManager 一文中我們正好對(duì)AuthenticationManager的機(jī)制有詳細(xì)的講解,所以要快速理解本文應(yīng)該去看看這一篇。
其中登錄認(rèn)證憑據(jù)封裝為UsernamePasswordAuthenticationToken?然后根據(jù) Token 的類型找到對(duì)應(yīng)的AuthenticationProvider進(jìn)行認(rèn)證。

3. OAuth2 對(duì)應(yīng)的 AuthenticationProvider
那么 OAuth2 登錄有異曲同工之妙,我們需要找到OAuth2LoginAuthenticationToken對(duì)應(yīng)的AuthenticationProvider。這里找到了兩個(gè):
OAuth2LoginAuthenticationProviderOidcAuthorizationCodeAuthenticationProvider
這兩個(gè)各自對(duì)應(yīng)的場(chǎng)景是什么呢,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;
}
意思是說(shuō)scopes中如果包含了openid就直接返回null,不會(huì)被OAuth2LoginAuthenticationToken處理,而OidcAuthorizationCodeAuthenticationProvider中正好相反。根據(jù)以往文章的脈絡(luò)OAuth2LoginAuthenticationProvider就是我們需要的。
有興趣可了解基于OIDC的 OAuth2 認(rèn)證。
4. OAuth2LoginAuthenticationProvider
OAuth2LoginAuthenticationProvider實(shí)現(xiàn)了授權(quán)回調(diào)的認(rèn)證過(guò)程:

OAuth2LoginAuthenticationProvider 認(rèn)證流程
從上圖中我們可以看出具體認(rèn)證由OAuth2AuthorizationCodeAuthenticationProvider來(lái)負(fù)責(zé),認(rèn)證通過(guò)后會(huì)去獲取用戶的信息并封裝為OAuth2User,最終生成授權(quán)成功的OAuth2LoginAuthenticationToken。
基于篇幅的原因,下一篇我們會(huì)分析OAuth2AuthorizationCodeAuthenticationProvider的處理機(jī)制。系列博文請(qǐng)?jiān)L問(wèn)felord.cn
推薦關(guān)注本文作者:碼農(nóng)小胖哥
一個(gè)堅(jiān)持分享原創(chuàng)干貨的Java開(kāi)發(fā)者

【往期推薦】
2020-12-15
2020-12-15
2020-12-14
2020-12-14
2020-12-13
2020-12-13
﹀
﹀
﹀
深度內(nèi)容
推薦加入

素質(zhì)二連,走一個(gè)
