基于SSM的RBAC权限系统(2)-Shiro使用注解下AJAX交互临时解决方案

来源:互联网 发布:java 重写父类方法 编辑:程序博客网 时间:2024/06/05 16:37

基于SSM的RBAC权限系统(2)-Shiro使用注解下AJAX交互临时解决方案

如果有哪位大佬知道更好的办法请务必通知我!

背景

前几天开始用Shiro做权限系统,由于某种特殊原因,所以用了Shiro,但是后来发现Shiro如果权限不足的话都是直接跳转界面,怎么办?上网搜索大部分人指出可以通过重写FormAuthenticationFilter、AuthorizationFilter来扩展Shiro对AJAX的支持。

但是我把这些Filter打上断点后,发现进行权限判断的时候根本没进到里面!(使用的是1.3.2版本)
于是只能另辟蹊径,如果你用的不是注解的话,完全没必要这么这样干。

处理思路

一开始想通过交换SpringMVC的拦截器和shiro拦截器的进行处理,但是发现这样做很麻烦,而且不知道在拦截器中获取返回中的json数据。后来干脆让shiro把所有ajax的请求都放行,再在controller里面自己调用shiro的方法进行权限判断。
拿添加用户的例子:

   public Msg userAdd(@Valid User user, BindingResult result) throws Exception{   //以下为条件判断        Throwable t = new Throwable();        //t.getStackTrace()[0].getMethodName()获取当前运行方法的全名        boolean isHasPermission= PermissionUtil.hasPermission(this.getClass(),t.getStackTrace()[0].getMethodName());        if(!isHasPermission)            return Msg.noPermission().add("returnMsg","你没有获得权限[用户添加]");   //以上为条件判断        if (result.hasErrors()) {            String msg= MsgUtil.returnErrorMsg(result);            return Msg.reject().add("msg",msg);        }        boolean isUserNameExist = userService.checkUserNameExit(user.getName());        boolean isUserAccountExist = userService.checkUserAccountExit(user.getAccount());        HashMap<String, String> errorMap = new HashMap<>();        if(isUserNameExist){            errorMap.put("#add_name","昵称已经存在!");        }        if(isUserAccountExist){            errorMap.put("#add_account","帐号已经存在!");        }        if(isUserNameExist||isUserAccountExist){            return Msg.fail().add("errorMap",errorMap);        }else{            userService.insert(user);            return Msg.success();        }    }

再来看看PermissionUtil里面的方法

 public static boolean hasPermission(Class cur_class,String methodName) {        //获取当前类所有方法        Method[] methods = cur_class.getMethods();        Method method = null;        for (int i = 0; i < methods.length; i++) {            if (methodName.equals(methods[i].getName())) {//和传入方法名匹配                method = methods[i];                break;            }        }        //找到刚才提到的方法,并得到当前用户        Subject currentUser = SecurityUtils.getSubject();        //当前用户是否已经验证?        if (null != currentUser) {            if (method.isAnnotationPresent(ResponseBody.class)) {                if (method.isAnnotationPresent(RequiredPermission.class)) {                    Permission permission = ajaxMethodToUrl(method);                    boolean permitted = currentUser.isPermitted(permission.getExpression());                    if (!permitted) {                        return false;                    }                }            }            return true;        }        else{            return false;        }    }

完整项目地址

这是我第一个写的web项目,代码烂得飞起,仅供纪念,不做参考
带Shiro版:https://github.com/EnTaroAdunZ/ssm_rbac_shiro.git
不带Shiro版:https://github.com/EnTaroAdunZ/ssm_rbac.git

阅读全文
0 0
原创粉丝点击