shiro-ajax请求的权限处理

shiro-ajax请求的权限处理

shiro处理没有权限是跳转页面,而我们如果是ajax请求,我们希望是返回json数据 ajax请求会有一个请求头:X-Requested-With: XMLHttpRequest 需要自定义一个shiro的权限过滤器

自定义权限过滤器

public class AisellPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {

protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {

    Subject subject = getSubject(request, response);
    // If the subject isn't identified, redirect to login URL
    if (subject.getPrincipal() == null) {
        saveRequestAndRedirectToLogin(request, response);
    } else {
        //一.拿到请求头
        HttpServletRequest req = (HttpServletRequest)request;
        // 拿到响应头
        HttpServletResponse resp = (HttpServletResponse)response;
        //设置响应头
        resp.setContentType("application/json;charset=UTF-8");
        String xr = req.getHeader("X-Requested-With");
        //二.判断这个请求头是否是Ajax请求
        if(xr!=null && "XMLHttpRequest".equals(xr)){
            //返回一个json {"success":false,"msg":"权限不足,请充值!"}
            resp.getWriter().print("{\"success\":false,\"msg\":\"你的权限不足,请充值!\"}");
        }else {
            //普通请求:拿到没有权限的跳转路径,进行跳转
            String unauthorizedUrl = getUnauthorizedUrl();
            if (StringUtils.hasText(unauthorizedUrl)) {
                WebUtils.issueRedirect(request, response, unauthorizedUrl);
            } else {
                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        }
    }
    return false;
}

}

applicationContext-shiro.xml配置权限过滤器



   
      ...
       
       
           
               
           
       
   

   
   

修改过滤器配置

@Autowired
private IPermissionService permissionService;
public Map createFilterChainDefinitionMap(){

//拿到所有权限
List perms = permissionService.findAll();
//设置相应的权限
perms.forEach(p -> {
filterChainDefinitionMap.put(p.getUrl(), “aisellPerms[”+p.getSn()+"]");
});

}

你可能感兴趣的:(shiro-ajax请求的权限处理)