MyRealm V2.0(注:加上了权限字符串)


import com.aaa.entity.User;
import com.aaa.service.MenuService;
import com.aaa.service.UserService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * Created by cws
 *
 * @author Administrator
 */
@Slf4j
@Component
public class MyRealm extends AuthorizingRealm {

    private static final int ZERO = 0;

    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;

    /**
     * @Author : cws
     * @Description : 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("授权开始");
        User user = (User) principalCollection.getPrimaryPrincipal();
        //获取用户id 将权限字符串添加到授权对象中
        String userId = user.getId();
        //用户权限列表
        Set<String> permsSet = menuService.getPermissions(userId);
        //授权对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * @Author : cws
     * @Description : 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("认证开始");
        //获取所有身份验证成功的Realm名字
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        //查询用户信息userService.findByUserName(username)
        EntityWrapper<User> wrapper = new EntityWrapper<>();
        User user = userService.selectOne(wrapper.eq("username",username));
        //账号不存在4
        if (user == null) {
            throw new UnknownAccountException("用户名不正确");
        }
        //密码错误
        if (!password.equals(user.getPassword())) {
            throw new IncorrectCredentialsException("密码不正确");
        }
        //账号禁用
        if ("0".equals(user.getStatus())) {
            throw new LockedAccountException("用户待审核中,请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }
}
posted @ 2020-10-27 16:32  白描先生  阅读(119)  评论(0编辑  收藏  举报
}); });