Shiro使用之自定义realm的编写

//MyRealm继承与Shiro自带的AuthorizingRealm 类
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    private RoleService roleService;

    /**
    验证当前登录用户
    *
    **/
    @Override       
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //获取token的身份信息(如登录名)     
        String userName = (String)token.getPrincipal();
        //通过token的身份信息获取实体user
        User user = userService.getUserByName(userName);
        //为什么不是通过id查询?因为token令牌的getPrincipal()获得是身份信息,就好像是登录时输入的username,没有谁会输入id一样。
        //若果是自己进行登录的验证,把获取到user的id信息作为token的Principal,作为后续验证的凭据,思路应该可以,但是没试过。

        if(user!=null){
            //创建 (简单的验证信息) 包含(身份信息)、(凭证)、(realm域名)三个参数
            //return authcInfo 由父类进行验证
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUserName(),user.getUserPassword(),getName());
            return authcInfo;
        }else{
            return null;                
        }   
    }

    /**
    为当前登录的用户授予角色和权限
    *
    **/
    @Override       
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //获取    主身份信息(如账户)
        String userName = (String)principals.getPrimaryPrincipal();

        //创建简单的 授权信息
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        //根据用户名查询当前所拥有的角色
        Set<Role> roleSet = userService.getRole(userName);
        Set<String> roleString = new HashSet<String>();

        Set<String> permissions = new HashSet<String>();

        for(Role role : roleSet){
            roleString.add(role.getRoleName());
            permissions.add(roleService.getPermission(role.getRoleName()).getPermissionName());
        }

        //为什么只传rolename的Set集合,为不直接传Set<Role>?
        //因为Shiro没有setRole<Role>的设置,只有set<String>,所以只能将角色实例变成角色名传给info      
        authorizationInfo.setRoles(roleString);

        //shiro倒是有传Set<Permission>的设置,但是这个Permission的类型是Shiro框架自带的类,不是你自己创建的Permission类,两者不一定兼容
        //所以还是将Set<String>的permission传给info     
        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值