1. 程式人生 > 其它 >跨域設定

跨域設定

 // 設定springboot的跨域訪問

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
      // 設定允許跨域的路徑
        registry.addMapping("/**")
                // 設定允許跨域請求的域名
                .allowedOriginPatterns("*")
                // 是否允許cookie
                .allowCredentials(true)
                // 設定允許的請求方式
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                // 設定允許的header屬性
                .allowedHeaders("*")
                // 跨域允許時間
                .maxAge(3600);
    }
}



// 設定spring-security的跨域訪問

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) // 開啟授權驗證
public class SecurityConfig extends WebSecurityConfigurerAdapter {
            @Override
    protected void configure(HttpSecurity http) throws Exception {
       
        // 允許跨域
        http.cors();
    }
}