wjli
2024-04-10 81af4cff627b7ec1e125b90f4fd57392c6d70588
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package cn.exrick.xboot.core.config.security;
 
import cn.exrick.xboot.core.common.utils.ResultUtil;
import cn.hutool.extra.spring.SpringUtil;
import jodd.util.Base64;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
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;
import org.springframework.stereotype.Component;
 
/**
 * @author xfei
 * @date 2023/4/28 14:13
 */
public class DaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials()==null){
            throw new BadCredentialsException("密码为空");
        }
        String password= authentication.getCredentials().toString();
        password = Base64.decodeToString(password);
        if (!new BCryptPasswordEncoder().matches(password, userDetails.getPassword())) {
            throw new BadCredentialsException("密码错误");
        }
 
 
        UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), password);
        newAuthentication.setDetails(authentication.getDetails());
    }
 
    @Override
    protected UserDetails retrieveUser(String s, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken) throws AuthenticationException {
        UserDetails userDetails = SpringUtil.getBean(UserDetailsService.class).loadUserByUsername(s);
 
 
        return userDetails;
    }
}