1. 程式人生 > >SpringBoot2.0填坑(一):使用CROS解決跨域並解決swagger 訪問不了問題

SpringBoot2.0填坑(一):使用CROS解決跨域並解決swagger 訪問不了問題

簡介

公司後臺是採用SpringBoot2.0 搭建的微服務架構,前端框架用的是vue 使用前後端分離的開發方式,在開發聯調的時候需要進行跨域訪問,那麼使用CROS解決了跨域問題,但是swagger 卻用不了 具體解決方案請繼續往下看…

CROS跨域原理

跨域資源共享(CORS) 是一種機制,它使用額外的 HTTP 頭來告訴瀏覽器 讓執行在一個 origin (domain) 上的Web應用被准許訪問來自不同源伺服器上的指定的資源。當一個資源從與該資源本身所在的伺服器不同的域或埠請求一個資源時,資源會發起一個跨域 HTTP 請求。

CORS_principle.png

跨域資源共享( CORS )機制允許 Web 應用伺服器進行跨域訪問控制,從而使跨域資料傳輸得以安全進行。現代瀏覽器支援在 API 容器中(例如 XMLHttpRequest 或 Fetch )使用 CORS,以降低跨域 HTTP 請求所帶來的風險。

CorsConfig.java 配置

import com.boyang.dicloud.aop.CheckLoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
public class CorsConfig extends WebMvcConfigurationSupport {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 設定允許跨域的路徑
        registry.addMapping("/**")
                // 設定允許跨域請求的域名
                .allowedOrigins("*")
                // 是否允許證書 不再預設開啟
                .allowCredentials(true)
                // 設定允許的方法
                .allowedMethods("*")
                // 跨域允許時間
                .maxAge(3600);
    }
}

Swagger 訪問異常

Swagger 訪問異常.jpg

原因分析:不能訪問的原因的swagger的內建介面被攔截器攔下來了,需要將swagger加到攔截器的排除列表中。

CorsConfig.java 增加配置

    @Bean
    CheckLoginInterceptor localInterceptor() {
        return new CheckLoginInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login")
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

完美解決!

貢獻者

更多精彩內容可以關注“IT實戰聯盟”公號哦~~~