101captain
2022-06-21 3421ca9d6195a96d0e63b4acc2cc9a77fe1b5564
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package com.panzhihua.auth.handel;
 
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
 
import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
 
import com.panzhihua.auth.config.MyAESUtil;
import com.panzhihua.common.model.helper.AESUtil;
import com.panzhihua.common.utlis.AES;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
 
import com.panzhihua.common.model.vos.LoginUserInfoVO;
import com.panzhihua.common.model.vos.R;
import com.panzhihua.common.service.user.UserService;
 
/**
 * @program: springcloud_k8s_panzhihuazhihuishequ
 * @description: 登录认证
 * @author: huang.hongfa weixin hhf9596 qq 959656820
 * @create: 2020-11-24 16:14
 **/
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;
 
    private static String LOGIN_FAIL="LOGIN_FAIL_";
 
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取表单输入中返回的用户名
        String userName = (String)authentication.getPrincipal();
        String password =(String)authentication.getCredentials();
        try {
            password = MyAESUtil.Decrypt((String)authentication.getCredentials(),"Ryo7M3n8loC5Abcd");
        } catch (Exception e) {
            e.printStackTrace();
        }
        boolean flag= redisTemplate.hasKey(LOGIN_FAIL+userName);
        if(flag){
           Integer time= (Integer) redisTemplate.opsForValue().get(LOGIN_FAIL+userName);
           if(time>=5){
               redisTemplate.opsForValue().set(LOGIN_FAIL+userName,5, Duration.ofMinutes(5));
               throw new LockedException("登录错误超过限制,请五分钟后重试");
           }
        }
        // 查询用户是否存在
        R<LoginUserInfoVO> r = userService.getUserInfo(userName);
        if (r.getCode() != 200) {
            lockLogin(flag,userName);
            throw new UsernameNotFoundException("账号或密码错误");
        }
        LoginUserInfoVO loginUserInfoVO = r.getData();
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        Set<String> roles = loginUserInfoVO.getRoles();
        if (!ObjectUtils.isEmpty(roles)) {
            roles.forEach(s -> {
                grantedAuthorityList.add(new SimpleGrantedAuthority(s));
            });
        }
        if (ObjectUtils.isEmpty(loginUserInfoVO.getAccount())||ObjectUtils.isEmpty(password)) {
            lockLogin(flag,userName);
            throw new UsernameNotFoundException("账号或密码错误");
        }
        // 我们还要判断密码是否正确,这里我们的密码使用BCryptPasswordEncoder进行加密的
        if (!new BCryptPasswordEncoder().matches(password, loginUserInfoVO.getPassword())) {
            lockLogin(flag,userName);
            throw new BadCredentialsException("密码不正确");
        }
        // 还可以加一些其他信息的判断,比如用户账号已停用等判断
        if (loginUserInfoVO.getStatus().intValue() == 2) {
            throw new LockedException("该用户已被禁用");
        }
        // 维护最后登录时间
        userService.putUserLastLoginTime(loginUserInfoVO.getUserId());
        return new UsernamePasswordAuthenticationToken(loginUserInfoVO, password, grantedAuthorityList);
    }
 
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
 
    private void lockLogin(Boolean flag,String userName){
        if(flag){
            Integer time= (Integer) redisTemplate.opsForValue().get(LOGIN_FAIL+userName);
            redisTemplate.opsForValue().set(LOGIN_FAIL+userName,time+1, Duration.ofMinutes(5));
        }
        else {
            redisTemplate.opsForValue().set(LOGIN_FAIL+userName,1, Duration.ofMinutes(5));
        }
    }
}