springboot+shiro 02 - 异步ajax请求无权限时,返回json格式数据

 

博客: https://www.cnblogs.com/youxiu326/p/shiro-01.html

github:https://github.com/youxiu326/sb_shiro_session.git

 

在原有基础上添加 SimpleFormAuthenticationFilter

/**
 *  自定义过滤器,ajax请求数据 以json格式返回
 * Created by lihui on 2019/2/28.
 */
public class SimpleFormAuthenticationFilter extends FormAuthenticationFilter {

    private static final Logger log = LoggerFactory.getLogger(SimpleFormAuthenticationFilter.class);

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }
                return executeLogin(request, response);
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }
                return true;
            }
        } else {
            HttpServletRequest httpRequest = WebUtils.toHttp(request);

            if (isAjax(httpRequest)) {
                HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
                httpServletResponse.sendError(401);
                return false;
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Attempting to access a path which requires authentication.  Forwarding to the " +
                            "Authentication url [" + getLoginUrl() + "]");
                }
                saveRequestAndRedirectToLogin(request, response);
            }

            return false;
        }
    }

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

}

 

springboot+shiro 02 - 异步ajax请求无权限时,返回json格式数据_第1张图片

 

 

 

springboot+shiro 02 - 异步ajax请求无权限时,返回json格式数据_第2张图片

 

 在ShiroConfig中添加一行

 
   
 shiroFilterFactoryBean.getFilters().put("authc", new SimpleFormAuthenticationFilter());

 

login.html 修改




    
    
    登录页面



这是登录页面

编号:
密码:

登出


姓名:
编号:
密码:

去添加界面(admin角色可以访问)
去修改界面(admin角色可以访问)
去列表界面(admin和test 角色可以访问)
去开放界面(登录了可以访问)

 

没有添加 SimpleFormAuthenticationFilter 之前

 

添加SimpleFormAuthenticationFilter 之后 返回了自定义错误状态码401

springboot+shiro 02 - 异步ajax请求无权限时,返回json格式数据_第3张图片

 

转载于:https://www.cnblogs.com/youxiu326/p/shiro-02.html

你可能感兴趣的:(json,java,git)