Spring Boot Security自定義AuthenticationProvider

以下是一個簡單的示例,展示如何使用AuthenticationProvider自定義身份驗證。首先,創建一個繼承自標準AuthenticationProvider的類,并實現authenticate方法。

import com.kamier.security.web.service.MyUser;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;import java.util.HashMap;
import java.util.Map;public class MobilecodeAuthenticationProvider implements AuthenticationProvider {private UserDetailsService userDetailsService;@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {MobilecodeAuthenticationToken mobilecodeAuthenticationToken = (MobilecodeAuthenticationToken) authentication;String phone = mobilecodeAuthenticationToken.getPhone();String mobileCode = mobilecodeAuthenticationToken.getMobileCode();System.out.println("登陸手機號:" + phone);System.out.println("手機驗證碼:" + mobileCode);// 模擬從redis中讀取手機號對應的驗證碼及其用戶名Map dataFromRedis = new HashMap();dataFromRedis.put("code", "6789");dataFromRedis.put("username", "admin");// 判斷驗證碼是否一致if (!mobileCode.equals(dataFromRedis.get("code"))) {throw new BadCredentialsException("驗證碼錯誤");}// 如果驗證碼一致,從數據庫中讀取該手機號對應的用戶信息MyUser loadedUser = (MyUser) userDetailsService.loadUserByUsername(dataFromRedis.get("username"));if (loadedUser == null) {throw new UsernameNotFoundException("用戶不存在");} else {MobilecodeAuthenticationToken result = new MobilecodeAuthenticationToken(loadedUser, null, loadedUser.getAuthorities());return result;}}@Overridepublic boolean supports(Class> aClass) {return MobilecodeAuthenticationToken.class.isAssignableFrom(aClass);}public void setUserDetailsService(UserDetailsService userDetailsService) {this.userDetailsService = userDetailsService;}
}

?注意這里的supports方法,是實現多種認證方式的關鍵,認證管理器AuthenticationManager會通過這個supports方法來判定當前需要使用哪一種認證方式

上面的就是只支持MobilecodeAuthenticationToken

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;/*** 手機驗證碼認證信息,在UsernamePasswordAuthenticationToken的基礎上添加屬性 手機號、驗證碼*/
public class MobilecodeAuthenticationToken extends AbstractAuthenticationToken {private static final long serialVersionUID = 530L;private Object principal;private Object credentials;private String phone;private String mobileCode;public MobilecodeAuthenticationToken(String phone, String mobileCode) {super(null);this.phone = phone;this.mobileCode = mobileCode;this.setAuthenticated(false);}public MobilecodeAuthenticationToken(Object principal, Object credentials, Collection extends GrantedAuthority> authorities) {super(authorities);this.principal = principal;this.credentials = credentials;super.setAuthenticated(true);}public Object getCredentials() {return this.credentials;}public Object getPrincipal() {return this.principal;}public String getPhone() {return phone;}public String getMobileCode() {return mobileCode;}public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {if (isAuthenticated) {throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");} else {super.setAuthenticated(false);}}public void eraseCredentials() {super.eraseCredentials();this.credentials = null;}
}
用戶名密碼

針對用戶名密碼方式,我們可以直接使用自帶的DaoAuthenticationProvider以及對應的UsernamePasswordAuthenticationToken。

實現UserDetailService

UserDetailService服務用以返回當前登錄用戶的用戶信息,可以每一種認證方式實現對應的UserDetailService,也可以使用同一個。這里我們使用同一個UserDetailService服務。(在provider中指定調用哪一個UserDetailService)

最后

在配置器中我們去實例化一個認證管理器AuthenticationManager,這個認證管理器中包含了兩個認證器,分別是MobilecodeAuthenticationProvider(手機驗證碼)、DaoAuthenticationProvider(用戶名密碼)。

下面的只是名字不同改成自己的provider名字即可

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/42179.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/42179.shtml
英文地址,請注明出處:http://en.pswp.cn/web/42179.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【Adobe】Photoshop圖層的使用

Adobe Photoshop(簡稱PS)中的圖層是圖像處理中一個核心概念,它允許用戶以堆疊的方式組織圖像的不同部分,從而實現對圖像的復雜編輯和處理而不影響原始圖像。以下是關于Adobe Photoshop圖層的詳細介紹: 一、圖層的定義 圖層就像是透明的紙張,你可以在上面繪制、添加圖像…

YOLOv10改進 | EIoU、SIoU、WIoU、DIoU、FocusIoU等二十余種損失函數

一、本文介紹 這篇文章介紹了YOLOv10的重大改進,特別是在損失函數方面的創新。它不僅包括了多種IoU損失函數的改進和變體,如SIoU、WIoU、GIoU、DIoU、EIOU、CIoU,還融合了“Focus”思想,創造了一系列新的損失函數。這些組合形式的…

Android Init Language自學筆記

Android Init Language由五個元素組成:Acttions、Commands、Services、Options和Imports。 Actions和Services隱式聲明了一個新的section。所以的Commands和Options都屬于最近聲明的section。 Services具有唯一的名稱,如果重名會報錯。 Actions Acti…

解決Spring Boot中的高可用性設計

解決Spring Boot中的高可用性設計 大家好,我是微賺淘客系統3.0的小編,也是冬天不穿秋褲,天冷也要風度的程序猿! 1. 高可用性設計概述 1.1 什么是高可用性? 高可用性指系統在面對各種故障和異常情況時,仍…

獨立開發者系列(22)——API調試工具apifox的使用

接口的邏輯已經實現,需要對外發布接口,而發布接口的時候,我們需要能自己簡單調試接口。當然,其實自己也可以寫簡單的代碼調試自己的接口,因為其實就是簡單的request請求或者curl庫讀取,調整請求方式get或者…

如果MySQL出現 “Too many connections“ 錯誤,該如何解決?

當你想要連接MySQL時出現"Too many connections" 報錯的情況下,該如何解決才能如愿以償呢?都是哥們兒,就教你兩招吧! 1.不想重啟數據庫的情況下 你可以嘗試采取以下方法來解決: 增加連接數限制&#xff1a…

RxJava學習記錄

文章目錄 1. 總覽1.1 基本原理1.2 導入包和依賴 2. 操作符2.1 創建操作符2.2 轉換操作符2.3 組合操作符2.4 功能操作符 1. 總覽 1.1 基本原理 參考文獻 構建流:每一步操作都會生成一個新的Observable節點(沒錯,包括ObserveOn和SubscribeOn線程變換操作…

asp.netWebForm(.netFramework) CSRF漏洞

asp.netWebForm(.netFramework) CSRF漏洞 CSRF(Cross-Site Request Forgery)跨站請求偽造是一種常見的 Web 應用程序安全漏 洞,攻擊者通過誘使已認證用戶在受信任的網站上執行惡意操作,從而利用用戶的身份 執行未經授權的操作。攻…

echarts實現3D餅圖

先看下最終效果 實現思路 使用echarts-gl的曲面圖&#xff08;surface&#xff09;類型 通過parametric繪制曲面參數實現3D效果 代碼實現 <template><div id"surfacePie"></div> </template> <script setup>import {onMounted} fro…

簡單的找到自己需要的flutter ui 模板

簡單的找到自己需要的flutter ui 模板 網站 https://flutterawesome.com/ 簡介 我原本以為會很難用 實際上不錯 很簡單 打開后界面類似于,右上角可以搜索 點擊view github 相當簡單 很oks

RabbitMq,通過prefetchCount限制消費并發數

1.問題:項目瓶頸,通過rabbitMq來異步上傳圖片,由于并發上傳的圖片過多導致阿里OSS異常, 解決方法:通過prefetchCount限制圖片上傳OSS的并發數量 2.定義消費者 Component AllArgsConstructor Slf4j public class ReceiveFaceImageEvent {private final UPloadService uploadSe…

【見刊通知】MVIPIT 2023機器視覺、圖像處理與影像技術國際會議

MVIPIT 2023&#xff1a;https://ieeexplore.ieee.org/xpl/conhome/10578343/proceeding 入庫Ei數據庫需等20-50天左右 第二屆會議征稿啟動&#xff08;MVIPIT 2024&#xff09; The 2nd International Conference on Machine Vision, Image Processing & Imaging Techn…

MacOS和Windows中怎么安裝Redis

希望文章能給到你啟發和靈感&#xff5e; 如果覺得文章對你有幫助的話&#xff0c;點贊 關注 收藏 支持一下博主吧&#xff5e; 閱讀指南 開篇說明一、基礎環境說明1.1 硬件環境1.2 軟件環境 二、MacOS中Redis的安裝2.1 HomeBrew 安裝&#xff08;推薦&#xff09;2.2 通過官方…

70.WEB滲透測試-信息收集- WAF、框架組件識別(10)

免責聲明&#xff1a;內容僅供學習參考&#xff0c;請合法利用知識&#xff0c;禁止進行違法犯罪活動&#xff01; 內容參考于&#xff1a; 易錦網校會員專享課 上一個內容&#xff1a;69.WEB滲透測試-信息收集- WAF、框架組件識別&#xff08;9&#xff09; 關于waf相應的識…

arcgis js 4.x實現類似openalayers加載tilewms圖層效果

一、普通wms與tilewms區別 相同點&#xff1a;都是加載WMS服務。 不同點&#xff1a;TitleWMS會把當前可視窗口根據網格&#xff08;開發者可以在調用OpenLayers api的時候自定義&#xff09;切分&#xff0c;一片一片地返回回來&#xff0c;在前端進行整合。而ImageWMS則不會…

Springboot 配置 log4j 時的注意事項

感謝博主 https://www.cnblogs.com/fishlittle/p/17950944 依賴 SpringBoot 的 starter 自帶的是 logback 日志&#xff0c;若要使用 log4j2 日志&#xff0c;需要引入對應依賴。logback 日志和 log4j2 日志都是對 slf4j 門面的實現&#xff0c;只能存在一個&#xff0c;且必…

江協科技51單片機學習- p25 無源蜂鳴器

&#x1f680;write in front&#x1f680; &#x1f50e;大家好&#xff0c;我是黃桃罐頭&#xff0c;希望你看完之后&#xff0c;能對你有所幫助&#xff0c;不足請指正&#xff01;共同學習交流 &#x1f381;歡迎各位→點贊&#x1f44d; 收藏?? 留言&#x1f4dd;?…

環信IM實現小米、oppo推送詳細步驟

本文教大家集成環信IM后如何實現小米、oppo推送。 一、小米推送 步驟一、在小米開放平臺創建應用。 在 小米開放平臺 創建應用&#xff0c;開啟推送服務。詳見小米官方網站的 推送服務接入指南。 步驟二、上傳推送證書。 注冊完成后&#xff0c;需要在環信即時通訊云控制臺…

WebSocket 雙向通信

WebSocket 是一種在前端開發中用于實現雙向通信的網絡技術。它與傳統的 HTTP 請求-響應模式不同&#xff0c;允許客戶端和服務器之間實時、雙向的數據傳輸。 1. 實時性 能夠實現數據的即時推送和接收&#xff0c;無需輪詢服務器&#xff0c;大大降低了延遲。 2. 雙向通信 客…

LeetCode-刷題記錄-前綴和合集(本篇blog會持續更新哦~)

一、前綴和&#xff08;Prefix Sum&#xff09;算法概述 前綴和算法通過預先計算數組的累加和&#xff0c;可以在常數時間內回答多個區間和相關的查詢問題&#xff0c;是解決子數組和問題中的重要工具。 它的基本思想是通過預先計算和存儲數組的前綴和&#xff0c;可以在 O(1)…