通用框架平台,每个分支对应子通用框架平台,禁止Merge不同分支!! 分支版本区别见项目内readme.md
whycxzp
2021-01-15 86771052e3fc386dfbe393ccae9f5b9f6af75391
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
package com.whyc.realm;
 
import com.whyc.anotation.Realm;
import com.whyc.constant.SuperConstant;
import com.whyc.pojo.User;
import com.whyc.service.UserBridgeService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
 
import javax.annotation.PostConstruct;
 
/**
 * 实际处理认证授权,跟数据库交互
 */
@Realm
public class CustomRealm extends AuthorizingRealm {
 
    /**必须@Lazy注解,@Lazy与@Autowired组合,使得依赖于Service相关的Bean都是lazy-resolution proxy*/
    @Lazy
    @Autowired
    UserBridgeService userBridgeService;
 
    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();
        User user = userBridgeService.findPasswordAndSlatByUserName(userName);
        if(user.getId()==0){
            System.out.printf("账号不存在");
            throw new UnknownAccountException("账号不存在");
        }
 
        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),getName());
    }
 
    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        return userBridgeService.getAuthorizationInfo(user);
    }
 
    /**加密*/
    @PostConstruct
    public void initCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(SuperConstant.HASH_ALGORITHM);
        matcher.setHashIterations(SuperConstant.HASH_INTERATIONS);
        setCredentialsMatcher(matcher);
    }
}