Spring Cloud項目前後端分離跨域的操作

跨域問題,其實百度上面有一堆的解決方案

針對普通的情況其實百度上面的方案都是可行的。

我這裡主要介紹2種情況。

當然我這裡的配置都是基於網關的,而不是基於服務的。

1、沒有增加權限驗證。

2、增加瞭spring security的權限驗證(我這裡是基於keyCloak),增加瞭Authorization

首先我們介紹第一種情況的解決方法,這個很簡單,隻需要在啟動類裡面配置過濾器就可以解決。

@Bean
    public CorsFilter corsFilter() {
        //1.添加CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
          //放行哪些原始域
          config.addAllowedOrigin("*");
          //是否發送Cookie信息
          config.setAllowCredentials(true);
          //放行哪些原始域(請求方式)
          config.addAllowedMethod("*");
          //放行哪些原始域(頭部信息)
          config.addAllowedHeader("*");
          //暴露哪些頭部信息(因為跨域訪問默認不能獲取全部頭部信息)
          config.addExposedHeader("*");
 
        //2.添加映射路徑
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
 
        //3.返回新的CorsFilter.
        return new CorsFilter(configSource);
    }

我遇到情況就是第二種瞭,這種情況上面的方式基本沒有作用,我這裡使用的是keyCloak做的權限驗證。

首先增加過濾器配置:

@Component
public class CorsControllerFilter implements Filter{
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
 
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletResponse res = (HttpServletResponse) response;
		res.setContentType("text/html;charset=UTF-8");
		res.setHeader("Access-Control-Allow-Origin", "*");
		res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE ,PUT");
		res.setHeader("Access-Control-Max-Age", "3600");
		res.setHeader("Access-Control-Allow-Headers", "*");
		res.setHeader("Access-Control-Allow-Credentials", "true");
		res.setHeader("XDomainRequestAllowed", "1");
		chain.doFilter(request, response);
	}
 
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub	
	}
}

在啟動類中增加配置

    @Bean
 public FilterRegistrationBean filterRegistrationBean() {
     FilterRegistrationBean registrationBean = new FilterRegistrationBean();
     CorsControllerFilter corsControllerFilter = new CorsControllerFilter();
     registrationBean.setFilter(corsControllerFilter);
     return registrationBean;
 }

但是針對某些請求,他會先請求OPTIONS請求,造成權限驗證失敗。所以增加攔截器配置,對所有的OPTIONS的請求直接放行,返回200的狀態。

public class OptionsInterceptor implements HandlerInterceptor {
 
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
	}
 
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
	}
 
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
        if(request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return false;
        }
        return true;
	}
}

配置web配置文件,加載攔截器。

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport{
 @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new OptionsInterceptor()).addPathPatterns("/**");
 }
}

本來以為這樣配置瞭應該是可以瞭,但是在請求的時候OPTIONS的請求居然還是報跨域的問題,增加攔截器允許跨域配置

public class CrossInterceptor implements HandlerInterceptor{
 @Override
 public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
   throws Exception {
  // TODO Auto-generated method stub
 }
 
 @Override
 public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
   throws Exception {
  // TODO Auto-generated method stub
 }
 
 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  // TODO Auto-generated method stub
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, HEAD");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        return true;
 }
}

在WebMvcConfiguration裡面增加配置,註意要寫在OptionsInterceptor的前面

registry.addInterceptor(new CrossInterceptor()).addPathPatterns("/**");

繼續測試,跨域問題解決。對於原理其實我也不太清楚,歡迎各位溝通交流。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: