CAS实现SSO,解决AJAX请求跨域系列问题
场景及问题描述:
项目为前后端分离,后台项目使用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下
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowOrigin</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, POST, HEAD, PUT, DELETE</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
</init-param>
<init-param>
<param-name>cors.exposedHeaders</param-name>
<param-value>Set-Cookie</param-value>
</init-param>
<init-param>
<param-name>cors.supportsCredentials</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
注意:如果只进行第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.