场景及问题描述:
项目为前后端分离,后台项目使用Spring Boot框架整合了CAS Client。前端发起ajax请求到CAS Client,被CAS Filter拦截器重定向到CAS Server,出现CORS跨域问题 。
错误信息:
Chrome F12完整错误信息:
Failed to load [CAS client地址]: Redirect from '[CAS client地址]' to '[CAS server地址]' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '[前端地址]' is therefore not allowed access.
Chrome F12关键错误信息:
No 'Access-Control-Allow-Origin' header is present on the requested resource
解决方案:
1、CAS Client中定义一个跨域Filter,注意:跨域Filter优先级必须要高于CAS FIlter,否则请求会先被CAS Filter先行执行,加跨域Filter则无意义。这里优先级设定为@Order(value=0),高于CAS FIlter。
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import java.io.IOException;
@Configuration
@Order(value=0)
@WebFilter(filterName = "CorsFilterConfig", urlPatterns = "/*")
public class CorsFilterConfig implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("===============CorsFilterConfig执行=================");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) servletResponse;
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
res.setHeader("Access-Control-Max-Age", "1728000");
res.setHeader("Access-Control-Allow-Headers",
"Authentication, Authorization, content-type, Accept, x-requested-with, Cache-Control");
filterChain.doFilter(servletRequest, res);
}
@Override
public void destroy() {}
}
2、CAS Server项目下找到web.xml,进行跨域Filter配置,但是需要下载java-property-utils和cors-filter jar包,放到lib下
CORS
com.thetransactioncompany.cors.CORSFilter
cors.allowOrigin
*
cors.supportedMethods
GET, POST, HEAD, PUT, DELETE
cors.supportedHeaders
Accept, Origin, X-Requested-With, Content-Type, Last-Modified
cors.exposedHeaders
Set-Cookie
cors.supportsCredentials
true
CORS
/*
注意:如果只进行第1步对CAS Client跨域配置,不进行第2步对CAS Server跨域配置,则会出现以下错误信息:
Failed to load [CAS server地址?service=url]: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
找了几篇CORS相关文章,感谢作者分享精神:
http://www.ruanyifeng.com/blog/2016/04/same-origin-policy.html
http://www.ruanyifeng.com/blog/2016/04/cors.html
https://www.cnblogs.com/keyi/p/6726089.html