带cookie的跨域解决方案

带cookie的跨域解决方案
本解决方案基于SpringBoot,首先编写FilterConfig类:

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author by mazhen
 * @Classname CorsFilterConfig
 * @Description TODO
 * @Date 2020/5/24 22:41
 */
@Configuration
public class CorsFilterConfig {

    @Bean
    public FilterRegistrationBean corsRegistration() {

        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        //所有的请求都经过此过滤器
        registrationBean.addUrlPatterns("/*");
        registrationBean.setFilter(new CorsFilter());
        return registrationBean;
    }
}

CorsFilter类如下:

import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author by mazhen
 * @Classname CorsFilter
 * @Description TODO
 * @Date 2020/5/24 23:29
 */
public class CorsFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String origin = req.getHeader("Origin");
        if (!StringUtils.isEmpty(origin)) {
            //带cookie的时候,origin必须是全匹配,不能使用*
            res.addHeader("Access-Control-Allow-Origin",origin);
        }
        
        String headers =  req.getHeader("Access-Control-Request-Headers");
        //支持所有请求头的跨域(包含自定义)
        if (!StringUtils.isEmpty(headers)) {
            res.addHeader("Access-Control-Allow-Headers",headers);
        }
        res.addHeader("Access-Control-Allow-Methods","*");
        //OPTIONS请求缓存3600秒
        res.addHeader("Access-Control-Max-Age","3600");
        //enable cookie
        res.addHeader("Access-Control-Allow-Credentials","true");
        filterChain.doFilter(req,res);
    }
}

CORS请求的简单请求和非简单请求
带cookie的跨域解决方案_第1张图片

你可能感兴趣的:(spring,SpringBoot,java,java,spring)