shiro 判断ajax是否通过身份验证

前端之家收集整理的这篇文章主要介绍了shiro 判断ajax是否通过身份验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这篇文章主要是针对使用shiro后ajax请求判断是否经过验证的问题。


代码:

public class RoleAuthorizationFilter extends AuthenticationFilter {

    private static int bytes = 1024;
    private static int startByte = 0;
    private static int endByte = 0;

    /** * shiro 授权失败会进入此方法 判断是否是ajax请求 */
    @Override
    protected boolean onAccessDenied(ServletRequest request,ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String serlvetPath = httpRequest.getServletPath();
        Subject subject = getSubject(request,response);
        if (subject.getPrincipal() == null) {
            // 这里判断是否为ajax请求且是以.do结尾的
            // 如果不是会走shiro默认的权限流程 
            if (isAjax(httpRequest) && serlvetPath.contains(".do")) {
                returnJsonResult(httpResponse,"您尚未登录登录时间过长,请重新登录!");
            } else {
                saveRequestAndRedirectToLogin(request,response);

            }
        }
        return false;
    }

    private void returnJsonResult(HttpServletResponse httpResponse,String message) {
        httpResponse.setStatus(301);
        httpResponse.setHeader("Content-type","application/json;charset=UTF-8");
        Result result = new Result();
        result.setCode(Const.FAIL);
        result.setMessage(message);
        Gson gson = new Gson();
        String jsonStr = gson.toJson(result);
        try {
            OutputStream os = httpResponse.getOutputStream();
            byte[] jsonByte = jsonStr.getBytes("UTF-8");
            int count = jsonByte.length;
            while (count > 0) {
                if (count < 1024) {
                    endByte = endByte + count;
                } else {
                    endByte = endByte + bytes;
                }
                os.write(jsonByte,startByte,endByte);
                startByte = endByte;
                count = count - bytes;
            }
        } catch (Exception e) {
        }

    }

    /** * 判断ajax请求 * * @param request * @return */
    private boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null
                && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
    }

}

这里说明saveRequestAndRedirectToLogin

进入这个方法是会将当前的请求redirect到spring-shiro.xml配置中的loginUrl

猜你在找的Ajax相关文章