上次我們把驗證碼登錄、小程式登錄優雅地集成到了Spring Security,很多同學大呼過癮,相比較一些傳統玩法高級了很多,胖哥就趕緊抓住機會舉一反三,把幾個非標準的OAuth2也接入了進來,主要是微信、企業微信,做到應接盡接,
只需要通過下面幾行簡單的代碼就可以完成集成:
@Bean
DelegateClientRegistrationRepository delegateClientRegistrationRepository(@Autowired(required = false) OAuth2ClientProperties properties) {
DelegateClientRegistrationRepository clientRegistrationRepository = new DelegateClientRegistrationRepository();
if (properties != null) {
List<ClientRegistration> registrations = new ArrayList<>(
OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties).values());
registrations.forEach(clientRegistrationRepository::addClientRegistration);
}
return clientRegistrationRepository;
}
這個是為了兼容在application.yaml組態檔的OAuth2客戶端配置、預設的微信等知名三方配置,你還可以通過DelegateClientRegistrationRepository的setDelegate方法來擴展獲取客戶端配置的方式:
public void setDelegate(Function<String, ClientRegistration> delegate) {
this.delegate = delegate;
}
然后在HttpSecurity中你這樣配置就完全OK了:
httpSecurity.apply(new OAuth2ProviderConfigurer(delegateClientRegistrationRepository))
// 微信網頁授權 下面的引數是假的
.wechatWebclient("wxdf90xxx8e7f", "bf1306baaaxxxxx15eb02d68df5")
// 企業微信登錄 下面的引數是假的
.workWechatWebLoginclient("wwa70dc5b6e56936e1",
"nvzGI4Alp3xxxxxxZUc3TtPtKbnfTEets5W8", "1000005")
// 微信掃碼登錄 下面的引數是假的
.wechatWebLoginclient("xxxxxxxx", "xxxxxxxx")
.oAuth2LoginConfigurerConsumer(oauth2Configurer->
oauth2Configurer.successHandler(new ForwardAuthenticationSuccessHandler("/"))
);
把帳號配置進去就完事了,簡單不簡單,而且擴展性依然有保障,完全能夠滿足你的個性化需求,如果你想資料庫管理這些引數,你可以自行擴展一下,也不難,
登錄的效果成這樣:

稍微一改成自定義頁面,是不是高大上起來了呢?

登錄成功后的邏輯,你可以寫一個/介面:
@GetMapping("/")
public Map<String, Object> index(@RegisteredOAuth2AuthorizedClient
OAuth2AuthorizedClient oAuth2AuthorizedClient) {
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
Map<String, Object> map = new HashMap<>(2);
// OAuth2AuthorizedClient 為敏感資訊不應該回傳前端
map.put("oAuth2AuthorizedClient", oAuth2AuthorizedClient);
map.put("authentication", authentication);
// todo 處理登錄注冊的邏輯 處理權限問題
// todo 根據 authentication 生成 token cookie之類的
// todo 也可以用 AuthenticationSuccessHandler 配置來替代
return map;
}
根據Authentication資訊回傳token也好、cookie也好,都能實作,你也可以不寫介面,配置一個AuthenticationSuccessHandler,
如果你有其它第三方OAuth2要對接,可以提供給胖哥配置,胖哥幫你免費搞定,
專案和DEMO地址是:https://gitee.com/felord/spring-security-login-extension 記得給個star哦!
關注公眾號:Felordcn 獲取更多資訊
個人博客:https://felord.cn
|
博主:碼農小胖哥 出處:felord.cn 本文著作權歸原作者所有,不可商用,轉載需要宣告出處,否則保留追究法律責任的權利,如果文中有什么錯誤,歡迎指出,以免更多的人被誤導, |
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/491811.html
標籤:Java
下一篇:Java常用類-包裝類
