XiaoRuby
2023-07-07 efbed347c8b659ca13207a1dbe34e77fdb003949
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
package com.yuanchu.limslaboratory.shiro.realm;
 
import com.yuanchu.limslaboratory.pojo.User;
import com.yuanchu.limslaboratory.service.UserService;
import com.yuanchu.limslaboratory.utils.MyUtils;
import com.yuanchu.limslaboratory.utils.SpringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.util.ObjectUtils;
 
public class ShiroRealm extends AuthorizingRealm {
 
    public User user;
 
    /**
     * 限定这个 Realm 只处理 UsernamePasswordToken
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
 
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
 
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        String principal = (String) authenticationToken.getPrincipal();
        //获取UserService对象
        UserService userService = SpringUtils.getBean(UserService.class);
        user = userService.AccordingUsernameSelectAll(principal);
        MyUtils.PrintLog(user.toString());
        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getAccount(), user.getPassword(), this.getName());
        } else {
            throw new UnknownAccountException();
        }
    }
 
    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
//        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
//        //设置使用MD5加密算法
//        hashedCredentialsMatcher.setHashAlgorithmName(Md5Hash.ALGORITHM_NAME);
//        //散列次数
//        hashedCredentialsMatcher.setHashIterations(1024);
//        super.setCredentialsMatcher(hashedCredentialsMatcher);
        super.setCredentialsMatcher(credentialsMatcher);
    }
}