Shiro拦截AJAX的解决方案

Shiro拦截AJAX的解决方案

最近在springboot项目上使用了shiro,但是shiro配置好后都是默认页面重定向处理。然而前后端分离后,静态页面都是部署在nginx上,统一都通过ajax进行调用。ajax的话不能进行重定向,需要返回指定格式的JSON。所以shiro需要满足一下几点要求:
  • ajax调用接口没有登录时,返回指定格式JSON

  • ajax调用接口在登录的情况下,没有权限时,返回指定格式JSON

  • 普通请求调用接口则进行重定向处理


Shiro的Filter拦截器

这时候需要扩展一下Shiro的Filter,主要有AdviceFilter、RolesAuthorizationFilter、PermissionsAuthorizationFilter

  • AdviceFilter有点类似SpringMVC中的HandlerInterceptor拦截器,主要用于在访问Controller之前用于判断用户是否登录
  • RolesAuthorizationFilter主要扩展了在shiro在认证Roles失败时回调的onAccessDenied方法,用于返回JSON或是重定向,也是需要我们实现的。
  • PermissionsAuthorizationFilter主要是认证perms资源,也是一样重写onAccessDenied方法

下图为Shiro的Filter关系图
Shiro拦截AJAX的解决方案_第1张图片

  • 可以看到AccessControllerFilter主要是Shiro控制认证和授权的过滤器

Filter拦截器的实现

扩展AdviceFilter,用于ajax访问接口未登录的处理

class ShiroLoginFilter extends AdviceFilter {

    /**
     * 在访问controller前判断是否登录,返回json,不进行重定向。
     * @param request
     * @param response
     * @return true-继续往下执行,false-该filter过滤器已经处理,不继续执行其他过滤器
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        SysUser sysUser = (SysUser) httpServletRequest.getSession().getAttribute("user");
        if (null == sysUser && !StringUtils.contains(httpServletRequest.getRequestURI(), "/login")) {
            String requestedWith = httpServletRequest.getHeader("X-Requested-With");
            if (StringUtils.isNotEmpty(requestedWith) && StringUtils.equals(requestedWith, "XMLHttpRequest")) {//如果是ajax返回指定数据
                ResponseHeader responseHeader = new ResponseHeader();
                responseHeader.setResponse(ResponseHeader.SC_MOVED_TEMPORARILY, null);
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.getWriter().write(JSONObject.toJSONString(responseHeader));
                return false;
            } else {//不是ajax进行重定向处理
                httpServletResponse.sendRedirect("/login/local");
                return false;
            }
        }
        return true;
    }

}

扩展RolesAuthorizationFilter,用于ajax访问接口登录但是角色认证不通过的处理
public class ShiroRolesFilter extends RolesAuthorizationFilter {

   class ShiroLoginFilter extends AdviceFilter {

    /**
     * 在访问controller前判断是否登录,返回json,不进行重定向。
     * @param request
     * @param response
     * @return true-继续往下执行,false-该filter过滤器已经处理,不继续执行其他过滤器
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String requestedWith = httpServletRequest.getHeader("X-Requested-With");
        if (StringUtils.isNotEmpty(requestedWith) &&
                StringUtils.equals(requestedWith, "XMLHttpRequest")) {//如果是ajax返回指定格式数据
            ResponseHeader responseHeader = new ResponseHeader();
            responseHeader.setResponse(ResponseHeader.SC_FORBIDDEN, null);
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json");
            httpServletResponse.getWriter().write(JSONObject.toJSONString(responseHeader));
        } else {//如果是普通请求进行重定向
            httpServletResponse.sendRedirect("/403");
        }
        return false;
    }
}

同样扩展PermissionsAuthorizationFilter,用于ajax访问接口登录但是资源操作认证不通过的处理

public class ShiroPermsFilter extends PermissionsAuthorizationFilter {
    /**
     * shiro认证perms资源失败后回调方法
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws IOException
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String requestedWith = httpServletRequest.getHeader("X-Requested-With");
        if (StringUtils.isNotEmpty(requestedWith) &&
                StringUtils.equals(requestedWith, "XMLHttpRequest")) {//如果是ajax返回指定格式数据
            ResponseHeader responseHeader = new ResponseHeader();
            responseHeader.setResponse(ResponseHeader.SC_FORBIDDEN, null);
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json");
            httpServletResponse.getWriter().write(JSONObject.toJSONString(responseHeader));
        } else {//如果是普通请求进行重定向
            httpServletResponse.sendRedirect("/403");
        }
        return false;
    }
}

最后在配置中将上面自定义的Filter设置到ShiroFilterFactoryBean。由于我的是springboot都是在java代码配置


    @Bean(name = "shiroLoginFilter")
    public ShiroLoginFilter shiroLoginFilter(){
        ShiroLoginFilter shiroLoginFilter = new ShiroLoginFilter();
        return shiroLoginFilter;
    }

Shiro拦截AJAX的解决方案_第2张图片

Filter配置后,Shiro处理用户请求的流程如下

Shiro拦截AJAX的解决方案_第3张图片

注意点

  • 在实现自定义Filter的时候不要用Spring进行单例模式的bean初始化,不然在认证的时候SecurityUtils.getSubject()会抛出:
    org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration.
    看着错误信息好像就是不要使用单例模式。具体查看: [ Spring Boot:取消Filter自动注册 ]

你可能感兴趣的:(shiro,shiro,ajax,spring-boot)