SpringSecurity的自定義用戶密碼驗證


我的用戶密碼前台輸入后,需要和用戶名關聯進行加密比較,所以重寫了AuthenticationProvider的實現類進行處理;

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private PasswordEncorder passwordEncorder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String presentedPassword = (String)authentication.getCredentials();
        UserDetails userDeatils = null;
// 根據用戶名獲取用戶信息 SysUser sysUser
= this.iSysUserService.getUserByName(username); if (StringUtils.isEmpty(sysUser)) { throw new BadCredentialsException("用戶名不存在"); } else { userDeatils = new User(username, sysUser.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList("USER"));
// 自定義的加密規則,用戶名、輸的密碼和數據庫保存的鹽值進行加密 String encodedPassword
= PasswordUtil.encrypt(username, presentedPassword, sysUser.getSalt()); if (authentication.getCredentials() == null) { throw new BadCredentialsException("登錄名或密碼錯誤"); } else if (!this.passwordEncorder.matches(encodedPassword, userDeatils.getPassword())) { throw new BadCredentialsException("登錄名或密碼錯誤"); } else { UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(userDeatils, authentication.getCredentials(), userDeatils.getAuthorities()); result.setDetails(authentication.getDetails()); return result; } } } @Override public boolean supports(Class<?> authentication) { return true; } }
然后在SecurityConfiguration配置中啟用
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(this.myAuthenticationProvider);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM