Java Code Examples for org.springframework.web.cors.CorsConfiguration

The following examples show how to use org.springframework.web.cors.CorsConfiguration. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: swagger-showdoc   Source File: CrossConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
   public FilterRegistrationBean corsFilter() {
       UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
       CorsConfiguration config = new CorsConfiguration();
       config.setAllowCredentials(true);
       // 设置你要允许的网站域名,如果全允许则设为 *
       config.addAllowedOrigin("*");
       // 如果要限制 HEADER 或 METHOD 请自行更改
       config.addAllowedHeader("*");
       config.addAllowedMethod("*");
       source.registerCorsConfiguration("/**", config);
       FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
       // 这个顺序很重要哦,为避免麻烦请设置在最前
       bean.setOrder(0);
       return bean;
}
 
Example 2
@Bean
public CorsConfigurationSource corsConfigurationSource() {
	final CorsConfiguration configuration = new CorsConfiguration();
	configuration.setAllowedOrigins(ImmutableList.of("*"));
	configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));

	// setAllowCredentials(true) is important, otherwise:
	// The value of the 'Access-Control-Allow-Origin' header in the response must
	// not be the wildcard '*' when the request's credentials mode is 'include'.
	configuration.setAllowCredentials(true);

	// setAllowedHeaders is important! Without it, OPTIONS preflight request
	// will fail with 403 Invalid CORS request
	configuration.setAllowedHeaders(ImmutableList.of("*"));

	final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
	source.registerCorsConfiguration("/**", configuration);
	return source;
}
 
Example 3
Source Project: SpringSecurity-JWT-Vue-Deom   Source File: WebSecurityConfig.java    License: MIT License 6 votes vote down vote up
/**
 * 跨域配置
 */
@Bean
public CorsConfigurationSource corsConfigurationSource() {
    // 允许跨域访问的 URL
    List<String> allowedOriginsUrl = new ArrayList<>();
    allowedOriginsUrl.add("http://localhost:8080");
    allowedOriginsUrl.add("http://127.0.0.1:8080");
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    // 设置允许跨域访问的 URL
    config.setAllowedOrigins(allowedOriginsUrl);
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return source;
}
 
Example 4
Source Project: balance-transfer-java   Source File: CorsConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public FilterRegistrationBean corsFilter() {
	UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
	CorsConfiguration config = new CorsConfiguration();
	config.setAllowCredentials(true);
	config.addAllowedOrigin("*");
	config.addAllowedHeader("*");
	config.addAllowedMethod("OPTIONS");
	config.addAllowedMethod("HEAD");
	config.addAllowedMethod("GET");
	config.addAllowedMethod("PUT");
	config.addAllowedMethod("POST");
	config.addAllowedMethod("DELETE");
	config.addAllowedMethod("PATCH");
	source.registerCorsConfiguration("/**", config);
	// return new CorsFilter(source);
	final FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
	bean.setOrder(0);
	return bean;
}
 
Example 5
Source Project: mall-tiny   Source File: GlobalCorsConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 允许跨域调用的过滤器
 */
@Bean
public CorsFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    //允许所有域名进行跨域调用
    config.addAllowedOrigin("*");
    //允许跨越发送cookie
    config.setAllowCredentials(true);
    //放行全部原始头信息
    config.addAllowedHeader("*");
    //允许所有请求方法跨域调用
    config.addAllowedMethod("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}
 
Example 6
Source Project: syndesis   Source File: SyndesisCorsConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public CorsFilter corsFilter() {
    return new CorsFilter(request -> {
        String pathInfo = request.getPathInfo();
        if (pathInfo != null &&
            (pathInfo.endsWith("/openapi.json") ||
             pathInfo.endsWith("/openapi.yaml"))) {
            return new CorsConfiguration().applyPermitDefaultValues();
        }

        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(allowedOrigins);
        config.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        config.applyPermitDefaultValues();
        return config;
    });
}
 
Example 7
@Override
protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
	HandlerMethod handlerMethod = createHandlerMethod(handler, method);
	Class<?> beanType = handlerMethod.getBeanType();
	CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(beanType, CrossOrigin.class);
	CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class);

	if (typeAnnotation == null && methodAnnotation == null) {
		return null;
	}

	CorsConfiguration config = new CorsConfiguration();
	updateCorsConfig(config, typeAnnotation);
	updateCorsConfig(config, methodAnnotation);

	if (CollectionUtils.isEmpty(config.getAllowedMethods())) {
		for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) {
			config.addAllowedMethod(allowedMethod.name());
		}
	}
	return config.applyPermitDefaultValues();
}
 
Example 8
/**
 * Look up a handler for the given request, falling back to the default
 * handler if no specific one is found.
 * @param request current HTTP request
 * @return the corresponding handler instance, or the default handler
 * @see #getHandlerInternal
 */
@Override
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
	Object handler = getHandlerInternal(request);
	if (handler == null) {
		handler = getDefaultHandler();
	}
	if (handler == null) {
		return null;
	}
	// Bean name or resolved handler?
	if (handler instanceof String) {
		String handlerName = (String) handler;
		handler = getApplicationContext().getBean(handlerName);
	}

	HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
	if (CorsUtils.isCorsRequest(request)) {
		CorsConfiguration globalConfig = this.corsConfigSource.getCorsConfiguration(request);
		CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
		CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
		executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
	}
	return executionChain;
}
 
Example 9
Source Project: java-technology-stack   Source File: CrossOriginTests.java    License: MIT License 6 votes vote down vote up
@Test
public void ambiguousProducesPreFlightRequest() throws Exception {
	this.handlerMapping.registerHandler(new MethodLevelController());
	this.request.setMethod("OPTIONS");
	this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
	this.request.setRequestURI("/ambiguous-produces");
	HandlerExecutionChain chain = this.handlerMapping.getHandler(request);
	CorsConfiguration config = getCorsConfiguration(chain, true);
	assertNotNull(config);
	assertArrayEquals(new String[] {"*"}, config.getAllowedMethods().toArray());
	assertArrayEquals(new String[] {"*"}, config.getAllowedOrigins().toArray());
	assertArrayEquals(new String[] {"*"}, config.getAllowedHeaders().toArray());
	assertTrue(config.getAllowCredentials());
	assertTrue(CollectionUtils.isEmpty(config.getExposedHeaders()));
	assertNull(config.getMaxAge());
}
 
Example 10
Source Project: spring-analysis-note   Source File: CrossOriginTests.java    License: MIT License 6 votes vote down vote up
@Test
public void ambiguousProducesPreFlightRequest() throws Exception {
	this.handlerMapping.registerHandler(new MethodLevelController());
	this.request.setMethod("OPTIONS");
	this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
	this.request.setRequestURI("/ambiguous-produces");
	HandlerExecutionChain chain = this.handlerMapping.getHandler(request);
	CorsConfiguration config = getCorsConfiguration(chain, true);
	assertNotNull(config);
	assertArrayEquals(new String[] {"*"}, config.getAllowedMethods().toArray());
	assertArrayEquals(new String[] {"*"}, config.getAllowedOrigins().toArray());
	assertArrayEquals(new String[] {"*"}, config.getAllowedHeaders().toArray());
	assertTrue(config.getAllowCredentials());
	assertTrue(CollectionUtils.isEmpty(config.getExposedHeaders()));
	assertNull(config.getMaxAge());
}
 
Example 11
Source Project: tutorials   Source File: WebConfigurer.java    License: MIT License 6 votes vote down vote up
@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = jHipsterProperties.getCors();
    if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
        log.debug("Registering CORS filter");
        source.registerCorsConfiguration("/api/**", config);
        source.registerCorsConfiguration("/management/**", config);
        source.registerCorsConfiguration("/v2/api-docs", config);
        source.registerCorsConfiguration("/auth/**", config);
        source.registerCorsConfiguration("/*/api/**", config);
        source.registerCorsConfiguration("/*/management/**", config);
        source.registerCorsConfiguration("/*/oauth/**", config);
    }
    return new CorsFilter(source);
}
 
Example 12
@Override
protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
	HandlerMethod handlerMethod = createHandlerMethod(handler, method);
	Class<?> beanType = handlerMethod.getBeanType();
	CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(beanType, CrossOrigin.class);
	CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class);

	if (typeAnnotation == null && methodAnnotation == null) {
		return null;
	}

	CorsConfiguration config = new CorsConfiguration();
	updateCorsConfig(config, typeAnnotation);
	updateCorsConfig(config, methodAnnotation);

	if (CollectionUtils.isEmpty(config.getAllowedMethods())) {
		for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) {
			config.addAllowedMethod(allowedMethod.name());
		}
	}
	return config.applyPermitDefaultValues();
}
 
Example 13
Source Project: hsweb-framework   Source File: CorsProperties.java    License: Apache License 2.0 6 votes vote down vote up
CorsConfiguration applyPermitDefaultValues() {
    if (this.allowedOrigins == null) {
        this.addAllowedOrigin();
    }
    if (this.allowedMethods == null) {
        this.setAllowedMethods(Arrays.asList(
                HttpMethod.GET.name(), HttpMethod.HEAD.name(), HttpMethod.POST.name()));
    }
    if (this.allowedHeaders == null) {
        this.addAllowedHeader();
    }
    if (this.allowCredentials == null) {
        this.setAllowCredentials(true);
    }
    if (this.maxAge == null) {
        this.setMaxAge(1800L);
    }
    return this;
}
 
Example 14
@Test
public void getCorsConfigurationPreFlight() throws Exception {
	AnnotationConfigWebApplicationContext cxt = new AnnotationConfigWebApplicationContext();
	cxt.register(TestConfig.class);
	cxt.refresh();

	// PRE-FLIGHT

	MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/path");
	request.addHeader("Origin", "http://localhost:9000");
	request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST");
	CorsConfiguration corsConfig = getIntrospector(cxt).getCorsConfiguration(request);

	assertNotNull(corsConfig);
	assertEquals(Collections.singletonList("http://localhost:9000"), corsConfig.getAllowedOrigins());
	assertEquals(Collections.singletonList("POST"), corsConfig.getAllowedMethods());
}
 
Example 15
Source Project: TeamDojo   Source File: WebConfigurer.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = jHipsterProperties.getCors();
    if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
        log.debug("Registering CORS filter");
        source.registerCorsConfiguration("/api/**", config);
        source.registerCorsConfiguration("/management/**", config);
        source.registerCorsConfiguration("/v2/api-docs", config);
    }
    return new CorsFilter(source);
}
 
Example 16
Source Project: spring-analysis-note   Source File: CorsWebFilter.java    License: MIT License 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
	ServerHttpRequest request = exchange.getRequest();
	CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(exchange);
	boolean isValid = this.processor.process(corsConfiguration, exchange);
	if (!isValid || CorsUtils.isPreFlightRequest(request)) {
		return Mono.empty();
	}
	return chain.filter(exchange);
}
 
Example 17
Source Project: teaching   Source File: WebMvcConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public CorsFilter corsFilter() {
	final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
	final CorsConfiguration corsConfiguration = new CorsConfiguration();
	/* 是否允许请求带有验证信息 */
	corsConfiguration.setAllowCredentials(true);
	/* 允许访问的客户端域名 */
	corsConfiguration.addAllowedOrigin("*");
	/* 允许服务端访问的客户端请求头 */
	corsConfiguration.addAllowedHeader("*");
	/* 允许访问的方法名,GET POST等 */
	corsConfiguration.addAllowedMethod("*");
	urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
	return new CorsFilter(urlBasedCorsConfigurationSource);
}
 
Example 18
Source Project: ZTuoExchange_framework   Source File: ApplicationConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedOrigin("*");
    config.setAllowCredentials(true);
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}
 
Example 19
Source Project: ZTuoExchange_framework   Source File: ContextConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public FilterRegistrationBean corsFilter() {
     UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
     CorsConfiguration config = new CorsConfiguration();
     config.addAllowedOrigin("*");
     config.setAllowCredentials(true);
     config.addAllowedHeader("*");
     config.addAllowedMethod("*");
     source.registerCorsConfiguration("/**", config);
     FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
     bean.setOrder(0);
     return bean;
}
 
Example 20
Source Project: open-capacity-platform   Source File: CorsConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 跨域支持
 *
 * @return
 */
@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true); // 允许cookies跨域
    config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许
    config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
    config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
    config.addAllowedMethod("*");// 允许提交请求的方法,*表示全部允许
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}
 
Example 21
@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setMaxAge(3600L);
    configuration.setAllowedOrigins(Collections.singletonList("*"));
    configuration.setAllowedMethods(Collections.singletonList("*"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(Collections.singletonList("*"));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", configuration);
    return source;
}
 
Example 22
Source Project: seata-demo   Source File: Startup.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}
 
Example 23
Source Project: spring-security-firebase   Source File: Application.java    License: MIT License 5 votes vote down vote up
@Bean
public CorsFilter corsFilter() {
	UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
	CorsConfiguration config = new CorsConfiguration();
	config.setAllowCredentials(true); // you USUALLY want this
	config.addAllowedOrigin("*");
	config.addAllowedHeader("*");
	config.addAllowedMethod("GET");
	config.addAllowedMethod("PUT");
	config.addAllowedMethod("POST");
	config.addAllowedHeader("x-firebase-auth");
	source.registerCorsConfiguration("/**", config);
	return new CorsFilter(source);
}
 
Example 24
Source Project: spring-analysis-note   Source File: AbstractHandlerMapping.java    License: MIT License 5 votes vote down vote up
/**
 * Retrieve the CORS configuration for the given handler.
 * @param handler the handler to check (never {@code null})
 * @param exchange the current exchange
 * @return the CORS configuration for the handler, or {@code null} if none
 */
@Nullable
protected CorsConfiguration getCorsConfiguration(Object handler, ServerWebExchange exchange) {
	if (handler instanceof CorsConfigurationSource) {
		return ((CorsConfigurationSource) handler).getCorsConfiguration(exchange);
	}
	return null;
}
 
Example 25
Source Project: klask-io   Source File: WebConfigurer.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "jhipster.cors.allowed-origins")
public CorsFilter corsFilter() {
    log.debug("Registering CORS filter");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = jHipsterProperties.getCors();
    source.registerCorsConfiguration("/api/**", config);
    source.registerCorsConfiguration("/v2/api-docs", config);
    source.registerCorsConfiguration("/oauth/**", config);
    return new CorsFilter(source);
}
 
Example 26
@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return source;
}
 
Example 27
Source Project: cubeai   Source File: WebConfigurer.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = jHipsterProperties.getCors();
    if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
        log.debug("Registering CORS filter");
        source.registerCorsConfiguration("/api/**", config);
        source.registerCorsConfiguration("/management/**", config);
        source.registerCorsConfiguration("/v2/api-docs", config);
    }
    return new CorsFilter(source);
}
 
Example 28
Source Project: mogu_blog_v2   Source File: SearchApplication.java    License: Apache License 2.0 5 votes vote down vote up
private CorsConfiguration buildConfig() {
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.addAllowedOrigin("*");
    corsConfiguration.addAllowedHeader("*");
    corsConfiguration.addAllowedMethod("*");
    return corsConfiguration;
}
 
Example 29
Source Project: open-capacity-platform   Source File: CorsConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true); // 允许cookies跨域
    config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许
    config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
    config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
    config.addAllowedMethod("*");// 允许提交请求的方法,*表示全部允许
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}
 
Example 30
Source Project: flash-waimai   Source File: CorsConfig.java    License: MIT License 5 votes vote down vote up
private CorsConfiguration buildConfig() {
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    //  你需要跨域的地址  注意这里的 127.0.0.1 != localhost
    // * 表示对所有的地址都可以访问
    corsConfiguration.addAllowedOrigin("*");
    //  跨域的请求头
    corsConfiguration.addAllowedHeader("*");
    //  跨域的请求方法
    corsConfiguration.addAllowedMethod("*");
    //加上了这一句,大致意思是可以携带 cookie
    //最终的结果是可以 在跨域请求的时候获取同一个 session
    corsConfiguration.setAllowCredentials(true);
    return corsConfiguration;
}