Springboot注解,SpringBoot Security 自定義登錄驗證邏輯+密碼加鹽

 2023-11-07 阅读 32 评论 0

摘要:密碼加鹽思路 JAVA 加鹽加密方法_Teln_小凱的博客-CSDN博客 Springboot注解。鹽加密方法 @ApiOperation(value = "002-加密")@PreAuthorize("hasAuthority('sys:app:all')")@GetMapping(value = "/encodePassword")publi

密碼加鹽思路

JAVA 加鹽加密方法_Teln_小凱的博客-CSDN博客

Springboot注解。鹽加密方法

@ApiOperation(value = "002-加密")@PreAuthorize("hasAuthority('sys:app:all')")@GetMapping(value = "/encodePassword")public HttpResult encodePassword(String password,String salt){String pwd = Md5Utils.md5Password(password,salt);pwd= new BCryptPasswordEncoder().encode(pwd);return HttpResult.oktoData(pwd);}

調用得到密文

?數據存鹽和密文

Spring boot,?下面開始修改從數據庫讀取,整體架構在下面這個基礎上修改

springboot security jwt restful_Teln_小凱的博客-CSDN博客

讀取數據庫的密碼、權限和鹽

?

重寫密碼加鹽的驗證

package com.java.core.web.security;import com.java.core.web.utils.Md5Utils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;/*** 身份驗證提供者*/
public class JwtAuthenticationProvider extends DaoAuthenticationProvider {public JwtAuthenticationProvider(UserDetailsService userDetailsService) {setUserDetailsService(userDetailsService);setPasswordEncoder(new BCryptPasswordEncoder());}@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {// 可以在此處覆寫整個登錄認證邏輯return super.authenticate(authentication);}@Overrideprotected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication)throws AuthenticationException {// 可以在此處覆寫密碼驗證邏輯//super.additionalAuthenticationChecks(userDetails, authentication);if (authentication.getCredentials() == null) {throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));} else {String presentedPassword = authentication.getCredentials().toString();presentedPassword=Md5Utils.md5Password(presentedPassword,((JwtUserDetails)userDetails).getSalt());if (!new BCryptPasswordEncoder().matches(presentedPassword, userDetails.getPassword())) {throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));}}}}

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://808629.com/169420.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 86后生记录生活 Inc. 保留所有权利。

底部版权信息