Spring Cloud項(xiàng)目前后端分離跨域的操作
針對(duì)普通的情況其實(shí)百度上面的方案都是可行的。
我這里主要介紹2種情況。當(dāng)然我這里的配置都是基于網(wǎng)關(guān)的,而不是基于服務(wù)的。
1、沒(méi)有增加權(quán)限驗(yàn)證。
2、增加了spring security的權(quán)限驗(yàn)證(我這里是基于keyCloak),增加了Authorization
首先我們介紹第一種情況的解決方法,這個(gè)很簡(jiǎn)單,只需要在啟動(dòng)類(lèi)里面配置過(guò)濾器就可以解決。
@Bean public CorsFilter corsFilter() {//1.添加CORS配置信息CorsConfiguration config = new CorsConfiguration(); //放行哪些原始域 config.addAllowedOrigin('*'); //是否發(fā)送Cookie信息 config.setAllowCredentials(true); //放行哪些原始域(請(qǐng)求方式) config.addAllowedMethod('*'); //放行哪些原始域(頭部信息) config.addAllowedHeader('*'); //暴露哪些頭部信息(因?yàn)榭缬蛟L問(wèn)默認(rèn)不能獲取全部頭部信息) config.addExposedHeader('*'); //2.添加映射路徑UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();configSource.registerCorsConfiguration('/**', config); //3.返回新的CorsFilter.return new CorsFilter(configSource); }
我遇到情況就是第二種了,這種情況上面的方式基本沒(méi)有作用,我這里使用的是keyCloak做的權(quán)限驗(yàn)證。
首先增加過(guò)濾器配置:
@Componentpublic class CorsControllerFilter implements Filter{@Overridepublic void destroy() {// TODO Auto-generated method stub} @Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {// TODO Auto-generated method stubHttpServletResponse 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);} @Overridepublic void init(FilterConfig arg0) throws ServletException {// TODO Auto-generated method stub}}
在啟動(dòng)類(lèi)中增加配置
@Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(); CorsControllerFilter corsControllerFilter = new CorsControllerFilter(); registrationBean.setFilter(corsControllerFilter); return registrationBean; }
但是針對(duì)某些請(qǐng)求,他會(huì)先請(qǐng)求OPTIONS請(qǐng)求,造成權(quán)限驗(yàn)證失敗。所以增加攔截器配置,對(duì)所有的OPTIONS的請(qǐng)求直接放行,返回200的狀態(tài)。
public class OptionsInterceptor implements HandlerInterceptor { @Overridepublic void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)throws Exception {// TODO Auto-generated method stub} @Overridepublic void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)throws Exception {// TODO Auto-generated method stub} @Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// TODO Auto-generated method stubif(request.getMethod().equals('OPTIONS')){ response.setStatus(HttpServletResponse.SC_OK); return false;}return true;}}
配置web配置文件,加載攔截器。
@Configurationpublic class WebMvcConfiguration extends WebMvcConfigurationSupport{ @Override public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new OptionsInterceptor()).addPathPatterns('/**'); }}
本來(lái)以為這樣配置了應(yīng)該是可以了,但是在請(qǐng)求的時(shí)候OPTIONS的請(qǐng)求居然還是報(bào)跨域的問(wèn)題,增加攔截器允許跨域配置
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 stubresponse.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里面增加配置,注意要寫(xiě)在OptionsInterceptor的前面
registry.addInterceptor(new CrossInterceptor()).addPathPatterns('/**');
繼續(xù)測(cè)試,跨域問(wèn)題解決。對(duì)于原理其實(shí)我也不太清楚,歡迎各位溝通交流。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Java commons-httpclient如果實(shí)現(xiàn)get及post請(qǐng)求2. 一文帶你徹底理解Java序列化和反序列化3. JS中6個(gè)對(duì)象數(shù)組去重的方法4. Python基于requests庫(kù)爬取網(wǎng)站信息5. vscode運(yùn)行php報(bào)錯(cuò)php?not?found解決辦法6. python中文本字符處理的簡(jiǎn)單方法記錄7. PHP laravel實(shí)現(xiàn)導(dǎo)出PDF功能8. Python使用Selenium自動(dòng)進(jìn)行百度搜索的實(shí)現(xiàn)9. PHP利用curl發(fā)送HTTP請(qǐng)求的實(shí)例代碼10. 資深程序員:給Python軟件開(kāi)發(fā)測(cè)試的25個(gè)忠告!

網(wǎng)公網(wǎng)安備