zoukankan      html  css  js  c++  java
  • shiro系列二、身份验证和授权

    一、身份验证

    先来看看身份验证的流程

    流程如下:

    1、首先调用Subject.login(token)进行登录,其会自动委托给Security Manager,调用之前必须通过SecurityUtils. setSecurityManager()设置;

    2、SecurityManager负责真正的身份验证逻辑;它会委托给Authenticator进行身份验证;

    3、Authenticator才是真正的身份验证者,Shiro API中核心的身份认证入口点,此处可以自定义插入自己的实现;

    4、Authenticator可能会委托给相应的AuthenticationStrategy进行多Realm身份验证,默认ModularRealmAuthenticator会调用AuthenticationStrategy进行多Realm身份验证;

    5、Authenticator会把相应的token传入Realm,从Realm获取身份验证信息,如果没有返回/抛出异常表示身份验证失败了。此处可以配置多个Realm,将按照相应的顺序及策略进行访问。

    测试案例:

    /**
         * 登录验证
         * @throws Exception 
         */
        @ResponseBody
        @RequestMapping(value = "/sys/login", method = RequestMethod.POST)
        public R login(String username, String password, String captcha)throws Exception {
        
            try{
                Subject subject = ShiroUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(username, password);
                subject.login(token);
            }catch (UnknownAccountException e) {
                return R.error(e.getMessage());
            }catch (IncorrectCredentialsException e) {
                return R.error("账号或密码不正确");
            }catch (LockedAccountException e) {
                return R.error("账号已被锁定,请联系管理员");
            }catch (AuthenticationException e) {
                return R.error("账户验证失败");
            }
            
            return R.ok();
        }

    2.5  Realm

    Realm:域,Shiro从从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源。如我们之前的ini配置方式将使用org.apache.shiro.realm.text.IniRealm。

    2.6  Authenticator及AuthenticationStrategy

    Authenticator的职责是验证用户帐号,是Shiro API中身份验证核心的入口点: 

    Java代码  
    1. public AuthenticationInfo authenticate(AuthenticationToken authenticationToken)  
    2.             throws AuthenticationException;   

    如果验证成功,将返回AuthenticationInfo验证信息;此信息中包含了身份及凭证;如果验证失败将抛出相应的AuthenticationException实现。

    SecurityManager接口继承了Authenticator,另外还有一个ModularRealmAuthenticator实现,其委托给多个Realm进行验证,验证规则通过AuthenticationStrategy接口指定,默认提供的实现:

    FirstSuccessfulStrategy:只要有一个Realm验证成功即可,只返回第一个Realm身份验证成功的认证信息,其他的忽略;

    AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和FirstSuccessfulStrategy不同,返回所有Realm身份验证成功的认证信息;

    AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有Realm身份验证成功的认证信息,如果有一个失败就失败了。

    二、 授权

    授权流程:

    流程如下:

    1、首先调用Subject.isPermitted*/hasRole*接口,其会委托给SecurityManager,而SecurityManager接着会委托给Authorizer;

    2、Authorizer是真正的授权者,如果我们调用如isPermitted(“user:view”),其首先会通过PermissionResolver把字符串转换成相应的Permission实例;

    3、在进行授权之前,其会调用相应的Realm获取Subject相应的角色/权限用于匹配传入的角色/权限;

    4、Authorizer会判断Realm的角色/权限是否和传入的匹配,如果有多个Realm,会委托给ModularRealmAuthorizer进行循环判断,如果匹配如isPermitted*/hasRole*会返回true,否则返回false表示授权失败。

    ModularRealmAuthorizer进行多Realm匹配流程:

    1、首先检查相应的Realm是否实现了实现了Authorizer;

    2、如果实现了Authorizer,那么接着调用其相应的isPermitted*/hasRole*接口进行匹配;

    3、如果有一个Realm匹配那么将返回true,否则返回false。

    如果Realm进行授权的话,应该继承AuthorizingRealm,其流程是:

    1.1、如果调用hasRole*,则直接获取AuthorizationInfo.getRoles()与传入的角色比较即可;

    1.2、首先如果调用如isPermitted(“user:view”),首先通过PermissionResolver将权限字符串转换成相应的Permission实例,默认使用WildcardPermissionResolver,即转换为通配符的WildcardPermission;

    2、通过AuthorizationInfo.getObjectPermissions()得到Permission实例集合;通过AuthorizationInfo. getStringPermissions()得到字符串集合并通过PermissionResolver解析为Permission实例;然后获取用户的角色,并通过RolePermissionResolver解析角色对应的权限集合(默认没有实现,可以自己提供);

    3、接着调用Permission. implies(Permission p)逐个与传入的权限比较,如果有匹配的则返回true,否则false。

    测试用例:

    /**
         * 授权(验证权限时调用)
         */
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            User user = (User)principals.getPrimaryPrincipal();
            Integer userId = user.getUserId();
            List<String> permsList = null;
            
            //系统管理员,拥有最高权限
            if(userId == 1){
                List<Auth> menuList = authService.queryList(new HashMap<String, Object>());
                permsList = new ArrayList<String>(menuList.size());
                for(Auth menu : menuList){
                    permsList.add(menu.getPerms());
                }
            }else{
                permsList = userService.queryAllPerms(userId);
            }
            //用户权限列表
            Set<String> permsSet = new HashSet<String>();
            for(String perms : permsList){
                if(StringUtils.isBlank(perms)){
                    continue;
                }
                permsSet.addAll(Arrays.asList(perms.trim().split(",")));
            }
            
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.setStringPermissions(permsSet);
            return info;
        }
  • 相关阅读:
    Twitter的分布式自增ID算法snowflake (Java版)
    quartz获取缓存中所有运行中的Job
    Git简易的命令入门
    Eclipse新建Maven工程——git篇
    Spring基于AspectJ的AOP的开发——注解
    Quartz-Spring定时任务器持久化,通过Service动态添加,删除,启动暂停任务
    用windows命令解压chm文件
    播放器
    ab压力测试
    自定义事件javascript
  • 原文地址:https://www.cnblogs.com/keepruning/p/9175822.html
Copyright © 2011-2022 走看看