前后端分离,shiro授权问题,ajax 请求返回401,非ajax请求返回login界面

springboot 整合shiro后,未授权的界面都会自动返回loginUrl,

今天搞前后端分离,前端需要接受401状态码, 查了一些资料,总结了一下自己的解决方法。

首先,网上有许多springboot 整合shiro的方法,就当环境中已经有了shiro.

解决思路: Shiro 的 有很多自带的 filter ,spring整合shiro后,会自动加载默认的filter,

1.继承 FormAuthenticationFilter 复写  onAccessDenied 方法

@Component
public class ShiroLoginFilter extends FormAuthenticationFilter {
    /**
     * 在访问controller前判断是否登录,返回401,不进行重定向。
     *
     * @param request
     * @param response
     * @return true-继续往下执行,false-该filter过滤器已经处理,不继续执行其他过滤器
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //加了一次过滤
        if (isAjax(request)) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json");
            httpServletResponse.setStatus(401);
            return false;
        }
        return super.onAccessDenied(request, response);
    }

    private boolean isAjax(ServletRequest request) {
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if ("XMLHttpRequest".equalsIgnoreCase(header)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

2 .加入自定义的filter

@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager,ShiroLoginFilter shiroLoginFilter) {
    ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
    shiroFilter.setSecurityManager(securityManager);
    // 加入自定义的filter
    Map filtersMap = new LinkedHashMap<>();
    filtersMap.put("shiroLoginFilter", shiroLoginFilter);
    shiroFilter.setFilters(filtersMap);
    
    shiroFilter.setLoginUrl("/login.html");
    shiroFilter.setUnauthorizedUrl("/");

    Map filterMap = new LinkedHashMap<>();
    filterMap.put("/swagger/**", "anon");
    filterMap.put("/v2/api-docs", "anon");
    filterMap.put("/swagger-ui.html", "anon");
    filterMap.put("/webjars/**", "anon");
    filterMap.put("/swagger-resources/**", "anon");
    filterMap.put("/csrf", "anon");

    filterMap.put("/statics/**", "anon");
    filterMap.put("/login.html", "anon");
    filterMap.put("/login", "anon");
    filterMap.put("/favicon.ico", "anon");
    filterMap.put("/captcha.jpg", "anon");
    filterMap.put("/**", "authc");
    shiroFilter.setFilterChainDefinitionMap(filterMap);

    return shiroFilter;
}

转载于:https://my.oschina.net/u/3293842/blog/3038061

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