Shiro Annotation保护实例

52 篇文章 0 订阅
2 篇文章 0 订阅

之前介绍了Shiro的Web访问控制和缓存配置,其实Shiro和Spring一样可以使用Annotation来配置方法级别的安全,省去自己每次获取Subject去做权限验证,比如在修改用户密码的时候只能是用户本人,在修改用户用户帐号的状态(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)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值