Shiro使用之自定义realm的编写

来源:互联网 发布:下拉框淘宝店铺搜索 编辑:程序博客网 时间:2024/05/21 10:45
//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