Shiro Annotation保护实例

之前介绍了Shiro的Web訪问控制和缓存配置,事实上Shiro和Spring一样能够使用Annotation来配置方法级别的安全。省去自己每次获取Subject去做权限验证,比方在改动用户password的时候仅仅能是用户本人。在改动用户用户帐号的状态(lock/unlock)仅仅有管理员能够,这些操作都须要方法级别的安全保护。
假设要自己获取当前的登录User信息,能够通过Shiro的SecurityUtils来实现。然后对User的权限做推断:

private User getCurrentUser(){
        Subject currentUser = SecurityUtils.getSubject();
        return userManager.getUserByName((String) currentUser.getPrincipal());
    }

假设使用Annotation。这些东西都是由Shiro来帮你实现了。你仅仅要在业务方法上面加上相应的权限管理,一般来说使用的是都是每一个对象的读写的权限,假设简单系统,能够把User相应的Role当成权限管理对象。给个简单样例:

 @Override
    @RequiresRoles("ROLE_ADMIN")
    public Show save(Show show){
       if(null != show.getId()){
            //due to create/update time is not passed back from page
            Show oldShow = findById(show.getId());
            if(null == oldShow){
                return null;
            }
            List<String> oldFilelist = LYTZUtils.getFilePathFromContent(oldShow.getContent());
            if(LOG.isDebugEnabled()){
                LOG.debug("the old content contains " + oldFilelist.size() + " images in image server");
            }
            show = super.save(show);
            List<String> newFilelist = LYTZUtils.getFilePathFromContent(show.getContent());
            for(String filePath : oldFilelist){
                if(!newFilelist.contains(filePath) && fileService.isFileExists(filePath)){
                    if(LOG.isDebugEnabled()){
                        LOG.debug("unusedFile: " + filePath);
                    }
                    fileService.removeFile(filePath);
                }
            }

            return show;
        } else {
            return super.save(show);
        }
    }

Shiro提供的annotation包含了基本验证:@RequiresAuthentication,@RequiresUser,@RequiresGuest ,角色验证:@RequiresRoles(value={“ROLE_VIP”, “ROLE_USER”}, logical= Logical.AND) ,@RequiresPermissions (value={“read”, “write”}, logical= Logical.OR)

原文地址:https://www.cnblogs.com/jzssuanfa/p/7357811.html