电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

Spring Security 密碼驗證動態加鹽的驗證處理方法

瀏覽:23日期:2023-07-11 10:47:35

本文個人博客地址:https://www.leafage.top/posts/detail/21697I2R

最近幾天在改造項目,需要將gateway整合security在一起進行認證和鑒權,之前gateway和auth是兩個服務,auth是shiro寫的一個,一個filter和一個配置,內容很簡單,生成token,驗證token,沒有其他的安全檢查,然后讓對項目進行重構。

先是要整合gateway和shiro,然而因為gateway是webflux,而shiro-spring是webmvc,所以沒搞成功,如果有做過并成功的,請告訴我如何進行整合,非常感謝。

那整合security呢,因為spring cloud gateway基于webflux,所以網上很多教程是用不了的,webflux的配置會有一些變化,具體看如下代碼示例:

import io.leafage.gateway.api.HypervisorApi;import io.leafage.gateway.handler.ServerFailureHandler;import io.leafage.gateway.handler.ServerSuccessHandler;import io.leafage.gateway.service.JdbcReactiveUserDetailsService;import org.springframework.context.annotation.Bean;import org.springframework.http.HttpMethod;import org.springframework.http.HttpStatus;import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;import org.springframework.security.config.web.server.ServerHttpSecurity;import org.springframework.security.core.userdetails.ReactiveUserDetailsService;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.web.server.SecurityWebFilterChain;import org.springframework.security.web.server.authentication.HttpStatusServerEntryPoint;import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;import org.springframework.security.web.server.authentication.logout.HttpStatusReturningServerLogoutSuccessHandler;import org.springframework.security.web.server.csrf.CookieServerCsrfTokenRepository;/** * spring security config . * * @author liwenqiang 2019/7/12 17:51 */@EnableWebFluxSecuritypublic class ServerSecurityConfiguration { // 用于獲取遠程數據 private final HypervisorApi hypervisorApi; public ServerSecurityConfiguration(HypervisorApi hypervisorApi) {this.hypervisorApi = hypervisorApi; } /** * 密碼配置,使用BCryptPasswordEncoder * * @return BCryptPasswordEncoder 加密方式 */ @Bean protected PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder(); } /** * 用戶數據加載 * * @return JdbcReactiveUserDetailsService 接口 */ @Bean public ReactiveUserDetailsService userDetailsService() {// 自定義的ReactiveUserDetails 實現return new JdbcReactiveUserDetailsService(hypervisorApi); } /** * 安全配置 */ @Bean SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {http.formLogin(f -> f.authenticationSuccessHandler(authenticationSuccessHandler()).authenticationFailureHandler(authenticationFailureHandler())).logout(l -> l.logoutSuccessHandler(new HttpStatusReturningServerLogoutSuccessHandler())).csrf(c -> c.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse())).authorizeExchange(a -> a.pathMatchers(HttpMethod.OPTIONS).permitAll().anyExchange().authenticated()).exceptionHandling(e -> e.authenticationEntryPoint(new HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED)));return http.build(); } /** * 登陸成功后執行的處理器 */ private ServerAuthenticationSuccessHandler authenticationSuccessHandler() {return new ServerSuccessHandler(); } /** * 登陸失敗后執行的處理器 */ private ServerAuthenticationFailureHandler authenticationFailureHandler() {return new ServerFailureHandler(); }}

上面的示例代碼,是我開源項目中的一段,一般的配置就如上面寫的,就可以使用了,但是由于我們之前的項目中的是shiro,然后有一個自定義的加密解密的邏輯。

首先說明一下情況,之前那一套加密(前端MD5,不加鹽,然后數據庫存儲的是加鹽后的數據和對應的鹽(每個賬號一個),要登錄比較之前對密碼要獲取動態的鹽,然后加鹽進行MD5,再進行對比,但是在配置的時候是沒法獲取某一用戶的鹽值)

所以上面的一版配置是沒法通過驗證的,必須在驗證之前,給請求的密碼混合該賬號對應的鹽進行二次加密后在對比,但是這里就有問題了:

security 框架提供的幾個加密解密工具沒有MD5的方式; security 配置加密解密方式的時候,無法填入動態的賬號的加密鹽;

對于第一個問題還好處理,解決方式是:自定義加密解密方式,然后注入到配置類中,示例如下:

import cn.hutool.crypto.SecureUtil;import com.ichinae.imis.gateway.utils.SaltUtil;import org.springframework.security.crypto.codec.Utf8;import org.springframework.security.crypto.password.PasswordEncoder;import java.security.MessageDigest;/** * 自定義加密解密 */public class MD5PasswordEncoder implements PasswordEncoder { @Override public String encode(CharSequence charSequence) {String salt = SaltUtil.generateSalt();return SecureUtil.md5(SecureUtil.md5(charSequence.toString()) + salt); } @Override public boolean matches(CharSequence charSequence, String encodedPassword) {byte[] expectedBytes = bytesUtf8(charSequence.toString());byte[] actualBytes = bytesUtf8(charSequence.toString());return MessageDigest.isEqual(expectedBytes, actualBytes); } private static byte[] bytesUtf8(String s) {// need to check if Utf8.encode() runs in constant time (probably not).// This may leak length of string.return (s != null) ? Utf8.encode(s) : null; }}

第二個問題的解決辦法,找了很多資料,也沒有找到,后來查看security的源碼發現,可以在UserDetailsService接口的findByUsername()方法中,在返回UserDetails實現的時候,使用默認實現User的UserBuilder內部類來解決這個問題,因為UserBuilder類中有一個屬性,passwordEncoder屬性,它是Fucntion<String, String>類型的,默認實現是 password -> password,即對密碼不做任何處理,先看下它的源碼:

Spring Security 密碼驗證動態加鹽的驗證處理方法

再看下解決問題之前的findByUsername()方法:

@Servicepublic class UserDetailsServiceImpl implements ReactiveUserDetailsService { @Resource private RemoteService remoteService; @Override public Mono<UserDetails> findByUsername(String username) {return remoteService.getUser(username).map(userBO -> User.builder().username(username).password(userBO.getPassword()).authorities(grantedAuthorities(userBO.getAuthorities())).build()); } private Set<GrantedAuthority> grantedAuthorities(Set<String> authorities) {return authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet()); }}

那找到了問題的解決方法,就來改代碼了,如下所示:

新增一個代碼處理方法

private Function<String, String> passwordEncoder(String salt) { return rawPassword -> SecureUtil.md5(rawPassword + salt);}

然后添加builder鏈

@Servicepublic class UserDetailsServiceImpl implements ReactiveUserDetailsService { @Resource private RemoteService remoteService; @Override public Mono<UserDetails> findByUsername(String username) {return remoteService.getUser(username).map(userBO -> User.builder().passwordEncoder(passwordEncoder(userBO.getSalt())) //在這里設置動態的鹽.username(username).password(userBO.getPassword()).authorities(grantedAuthorities(userBO.getAuthorities())).build()); } private Set<GrantedAuthority> grantedAuthorities(Set<String> authorities) {return authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet()); } private Function<String, String> passwordEncoder(String salt) {return rawPassword -> SecureUtil.md5(rawPassword + salt); }}

然后跑一下代碼,請求登錄接口,就登陸成功了。

Spring Security 密碼驗證動態加鹽的驗證處理方法

以上就是Spring Security 密碼驗證動態加鹽的驗證處理的詳細內容,更多關于Spring Security密碼驗證的資料請關注好吧啦網其它相關文章!

標簽: Spring
相關文章:
主站蜘蛛池模板: 杭州货架订做_组合货架公司_货位式货架_贯通式_重型仓储_工厂货架_货架销售厂家_杭州永诚货架有限公司 | 智能气瓶柜(大型气瓶储存柜)百科 | 泰国专线_泰国物流专线_广州到泰国物流公司-泰廊曼国际 | 郑州爱婴幼师学校_专业幼师培训_托育师培训_幼儿教育培训学校 | 液压压力机,液压折弯机,液压剪板机,模锻液压机-鲁南新力机床有限公司 | 全自动贴标机-套标机-工业热风机-不干胶贴标机-上海厚冉机械 | 并离网逆变器_高频UPS电源定制_户用储能光伏逆变器厂家-深圳市索克新能源 | 衡阳耐适防护科技有限公司——威仕盾焊接防护用品官网/焊工手套/焊接防护服/皮革防护手套 | 【铜排折弯机,钢丝折弯成型机,汽车发泡钢丝折弯机,线材折弯机厂家,线材成型机,铁线折弯机】贝朗折弯机厂家_东莞市贝朗自动化设备有限公司 | 瓶盖扭矩仪(扭力值检测)-百科 | 除甲醛公司-甲醛检测治理-杭州创绿家环保科技有限公司-室内空气净化十大品牌 | 帽子厂家_帽子工厂_帽子定做_义乌帽厂_帽厂_制帽厂 | 老房子翻新装修,旧房墙面翻新,房屋防水补漏,厨房卫生间改造,室内装潢装修公司 - 一修房屋快修官网 | 二维运动混料机,加热型混料机,干粉混料机-南京腾阳干燥设备厂 | 泰州物流公司_泰州货运公司_泰州物流专线-东鑫物流公司 | 闸阀_截止阀_止回阀「生产厂家」-上海卡比阀门有限公司 | 坏男孩影院-提供最新电影_动漫_综艺_电视剧_迅雷免费电影最新观看 | 上海单片机培训|重庆曙海培训分支机构—CortexM3+uC/OS培训班,北京linux培训,Windows驱动开发培训|上海IC版图设计,西安linux培训,北京汽车电子EMC培训,ARM培训,MTK培训,Android培训 | 电机铸铝配件_汽车压铸铝合金件_发动机压铸件_青岛颖圣赫机械有限公司 | ET3000双钳形接地电阻测试仪_ZSR10A直流_SXJS-IV智能_SX-9000全自动油介质损耗测试仪-上海康登 | 好看的韩国漫画_韩漫在线免费阅读-汗汗漫画| 航空连接器,航空插头,航空插座,航空接插件,航插_深圳鸿万科 | 铝箔-铝板-花纹铝板-铝型材-铝棒管-上海百亚金属材料有限公司 | 英语词典_成语词典_日语词典_法语词典_在线词典网 | TPU薄膜_TPU薄膜生产厂家_TPU热熔胶膜厂家定制_鑫亘环保科技(深圳)有限公司 | 雨燕360体育免费直播_雨燕360免费NBA直播_NBA篮球高清直播无插件-雨燕360体育直播 | 灌装封尾机_胶水灌装机_软管灌装封尾机_无锡和博自动化机械制造有限公司 | 机房监控|动环监控|动力环境监控系统方案产品定制厂家 - 迈世OMARA | Magnescale探规,Magnescale磁栅尺,Magnescale传感器,Magnescale测厚仪,Mitutoyo光栅尺,笔式位移传感器-苏州连达精密量仪有限公司 | [官网]叛逆孩子管教_戒网瘾学校_全封闭问题青少年素质教育_新起点青少年特训学校 | 河南15年专业网站建设制作设计,做网站就找郑州启凡网络公司 | 奶茶加盟,奶茶加盟店连锁品牌-甜啦啦官网| 空压机网_《压缩机》杂志| 除湿机|工业除湿机|抽湿器|大型地下室车间仓库吊顶防爆除湿机|抽湿烘干房|新风除湿机|调温/降温除湿机|恒温恒湿机|加湿机-杭州川田电器有限公司 | 工业机械三维动画制作 环保设备原理三维演示动画 自动化装配产线三维动画制作公司-南京燃动数字 聚合氯化铝_喷雾聚氯化铝_聚合氯化铝铁厂家_郑州亿升化工有限公司 | 北京律师事务所_房屋拆迁律师_24小时免费法律咨询_云合专业律师网 | 聚氨酯催化剂K15,延迟催化剂SA-1,叔胺延迟催化剂,DBU,二甲基哌嗪,催化剂TMR-2,-聚氨酯催化剂生产厂家 | 乐考网-银行从业_基金从业资格考试_初级/中级会计报名时间_中级经济师 | 视频直播 -摄影摄像-视频拍摄-直播分发| 会议会展活动拍摄_年会庆典演出跟拍_摄影摄像直播-艾木传媒 | 今日热点_实时热点_奇闻异事_趣闻趣事_灵异事件 - 奇闻事件 |