Springboot+shiro的跨域处理,亲测有用

一、在config包(一般与Controller,service,pojo等同级)下创建CORSFilter继承import org.apache.shiro.web.servlet.OncePerRequestFilter。这里面所有的放行不能用*必须得是具体的值,不然是无法跨域成功滴。

@Component
@Configuration
//解决Access-Control-Allow-Origin跨域问题
class CORSFilter extends OncePerRequestFilter {
    public void doFilterInternal(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setContentType("text/html;charset=UTF-8");

        res.setContentType("text/html;charset=UTF-8");

        response.setHeader("XDomainRequestAllowed","1");//不可以放在后面

        //放行所有,类似*,这里的*完全无效
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");

        //允许请求方式
        response.setHeader("Access-Control-Allow-Methods", "POST,PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");

        //需要放行header头部字段 如需鉴权字段,自行添加,如Authorization等
        response.setHeader("Access-Control-Allow-Headers",
                "content-type,x-requested-with,Authorization," +
                        "authorization,Origin,No-Cache,X-Requested-With,If-Modified-Since," +
                        " Pragma, Last-Modified, Cache-Control,Expires, Content-Type, X-E4M-With,userId,token");

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
     //请求预检放行--不能省
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return ;
        } else {
            chain.doFilter(request, response);
        }
    }
}

二、在shiro的配置类ShiroConfig(里面配置了放行哪些资源,访问哪些需要什么权限等的配置类)里面添加如下代码,不要忘记加注解@Bean

    @Bean
    public FilterRegistrationBean replaceTokenFilter(){
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter( new CORSFilter());
        registration.addUrlPatterns("/*");
        registration.setName("CrosFilter");
        registration.setOrder(1);
        return registration;
    }

三、输入网址测试,然后就可以看到正常跨域访问接口了,如果跨域不成功的话页面是一片空白报错Access-Control-Allow-Origin或者Access-Control-Allow-Headers等信息

Springboot+shiro的跨域处理,亲测有用

 

Springboot+shiro的跨域处理,亲测有用

上一篇:Windows下Eclipse+PyDev配置Python开发环境


下一篇:oeasy教您玩转vim - 23 - 配置文件