Java Code Examples for org.springframework.web.cors.CorsConfiguration#setAllowedHeaders()

The following examples show how to use org.springframework.web.cors.CorsConfiguration#setAllowedHeaders() . 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 File: WebSecurityConfiguration.java    From microservices-basics-spring-boot with Apache License 2.0 7 votes vote down vote up
@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 2
Source File: WebAutoConfig.java    From yue-library with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "yue.cors", name = "allow", havingValue = "true", matchIfMissing = true)
public CorsFilter corsFilter(CorsProperties corsProperties) {
	final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
	final CorsConfiguration config = new CorsConfiguration();
	
	config.setAllowCredentials(true);
	config.setAllowedHeaders(Arrays.asList("*"));
	config.setAllowedMethods(Arrays.asList("*"));
	config.setAllowedOrigins(Arrays.asList("*"));
	config.setMaxAge(3600L);
	
	// 设置response允许暴露的Headers
	List<String> exposedHeaders = corsProperties.getExposedHeaders();
	if (exposedHeaders != null) {
		config.setExposedHeaders(exposedHeaders);
	} else {
		config.addExposedHeader("token");
	}
	
	source.registerCorsConfiguration("/**", config);
	
	log.info("【初始化配置-跨域】默认配置为true,当前环境为true:默认任何情况下都允许跨域访问 ... 已初始化完毕。");
	return new CorsFilter(source);
}
 
Example 3
Source File: CorsMetadataProcessor.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
public void setCorsConfiguration(String serviceId, Map<String, String> metadata) {
    String isCorsEnabledForService = metadata.get("apiml.corsEnabled");
    if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource) {
        UrlBasedCorsConfigurationSource cors = (UrlBasedCorsConfigurationSource) this.corsConfigurationSource;
        final CorsConfiguration config = new CorsConfiguration();
        if (Boolean.parseBoolean(isCorsEnabledForService)) {
            config.setAllowCredentials(true);
            config.addAllowedOrigin(CorsConfiguration.ALL);
            config.setAllowedHeaders(Collections.singletonList(CorsConfiguration.ALL));
            config.setAllowedMethods(allowedCorsHttpMethods);
        }
        metadata.entrySet().stream()
            .filter(entry -> gatewayRoutesPattern.matcher(entry.getKey()).find())
            .forEach(entry ->
                cors.registerCorsConfiguration("/" + entry.getValue() + "/" + serviceId.toLowerCase() + "/**", config));
    }
}
 
Example 4
Source File: SecurityConfiguration.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Bean
CorsConfigurationSource corsConfigurationSource() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    List<String> pathsToEnable;
    if (corsEnabled) {
        addCorsRelatedIgnoredHeaders();

        config.setAllowCredentials(true);
        config.addAllowedOrigin(CorsConfiguration.ALL);
        config.setAllowedHeaders(Collections.singletonList(CorsConfiguration.ALL));
        config.setAllowedMethods(allowedCorsHttpMethods());
        pathsToEnable = CORS_ENABLED_ENDPOINTS;
    } else {
        pathsToEnable = Collections.singletonList("/**");
    }
    pathsToEnable.forEach(path -> source.registerCorsConfiguration(path, config));
    return source;
}
 
Example 5
Source File: LdapSecurityConfiguration.java    From data-highway with Apache License 2.0 6 votes vote down vote up
@Bean
public CorsConfigurationSource corsConfigurationSource() {
  CorsConfiguration configuration = new CorsConfiguration().applyPermitDefaultValues();
  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("Authorization", "Cache-Control", "Content-Type"));

  UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  source.registerCorsConfiguration("/**", configuration);
  return source;
}
 
Example 6
Source File: SecurityCorsConfiguration.java    From bootshiro with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.setAllowedOrigins(Arrays.asList(CorsConfiguration.ALL));
    corsConfiguration.setAllowedHeaders(Arrays.asList(CorsConfiguration.ALL));
    corsConfiguration.setAllowedMethods(Arrays.asList(CorsConfiguration.ALL));
    source.registerCorsConfiguration("/**", corsConfiguration);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
}
 
Example 7
Source File: ResourceServerMain.java    From spring-oauth-example with MIT License 5 votes vote down vote up
/**
 * This special filter is needed so unauthorized request that are rejected by Spring security
 * still have CORS headers.
 * For some reason he {@code bean.setOrder} call is not enough, the configuration also needs
 * {@code security.filter-order=5} for the CORS filter to be in front of the Spring Security
 * filter.
 */
@Bean
public FilterRegistrationBean corsFilter() {
    //based on https://github.com/spring-projects/spring-boot/issues/5834
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.setAllowedOrigins(Collections.singletonList("*"));
    config.setAllowedMethods(Collections.singletonList("*"));
    config.setAllowedHeaders(Collections.singletonList("*"));
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}
 
Example 8
Source File: CommonBeanConfiguration.java    From Insights with Apache License 2.0 5 votes vote down vote up
/**
 * used for CORS validation, A container for CORS configuration to validate
 * against the actual origin, HTTP methods, and headers of a given request.
 * 
 * @return
 */
@Bean
public CorsConfigurationSource corsConfigurationSource() {
	LOG.debug("Setting up corsConfigurationSource ");
	CorsConfiguration configuration = new CorsConfiguration();
	configuration.setAllowedOrigins(Arrays.asList("*"));
	configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "PUT", "DELETE", "PATCH"));
	configuration.setAllowCredentials(true);
	configuration.setAllowedHeaders(Arrays.asList("*"));
	UrlBasedCorsConfigurationSource sourceCors = new UrlBasedCorsConfigurationSource();
	sourceCors.registerCorsConfiguration("/**", configuration);
	return sourceCors;
}
 
Example 9
Source File: BasicSecurityConfigurerAdapter.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.setAllowedOrigins(getPropertiesAsList("http.cors.allow-origin", "*"));
    config.setAllowedHeaders(getPropertiesAsList("http.cors.allow-headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With, " + DEFAULT_CSRF_HEADER_NAME + ", " + DEFAULT_RECAPTCHA_HEADER_NAME));
    config.setAllowedMethods(getPropertiesAsList("http.cors.allow-methods", "OPTIONS, GET, POST, PUT, DELETE, PATCH"));
    config.setExposedHeaders(getPropertiesAsList("http.cors.exposed-headers", DEFAULT_CSRF_HEADER_NAME));
    config.setMaxAge(environment.getProperty("http.cors.max-age", Long.class, 1728000L));

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return source;
}
 
Example 10
Source File: SecurityProperties.java    From spring-oauth2-keycloak-connector with Apache License 2.0 5 votes vote down vote up
public CorsConfiguration getCorsConfiguration() {
  CorsConfiguration corsConfiguration = new CorsConfiguration();
  corsConfiguration.setAllowedOrigins(cors.getAllowedOrigins());
  corsConfiguration.setAllowedMethods(cors.getAllowedMethods());
  corsConfiguration.setAllowedHeaders(cors.getAllowedHeaders());
  corsConfiguration.setExposedHeaders(cors.getExposedHeaders());
  corsConfiguration.setAllowCredentials(cors.getAllowCredentials());
  corsConfiguration.setMaxAge(cors.getMaxAge());

  return corsConfiguration;
}
 
Example 11
Source File: WebSecurityConfig.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
/**
 * 跨域资源配置
 * @author Frodez
 * @date 2018-12-04
 */
@Bean
public CorsConfigurationSource corsConfigurationSource() {
	CorsConfiguration configuration = new CorsConfiguration();
	Cors cors = properties.getCors();
	configuration.setAllowedOrigins(cors.getAllowedOrigins());
	configuration.setAllowedMethods(cors.getAllowedMethods());
	configuration.setAllowedHeaders(cors.getAllowedHeaders());
	UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
	source.registerCorsConfiguration("/**", configuration);
	return source;
}
 
Example 12
Source File: DevelopmentConfig.java    From eds-starter6-jpa with Apache License 2.0 5 votes vote down vote up
@Bean
public FilterRegistrationBean<CorsFilter> corsFilterRegistration() {
	FilterRegistrationBean<CorsFilter> filter = new FilterRegistrationBean<>();
	CorsConfiguration config = new CorsConfiguration();
	config.setAllowedOrigins(Collections.singletonList(CorsConfiguration.ALL));
	config.setAllowedMethods(Collections.singletonList(CorsConfiguration.ALL));
	config.setAllowedHeaders(Collections.singletonList(CorsConfiguration.ALL));
	config.setAllowCredentials(true);
	filter.setFilter(new CorsFilter(r -> config));
	filter.setUrlPatterns(Collections.singleton("/*"));
	filter.setOrder(SecurityProperties.DEFAULT_FILTER_ORDER - 1);
	return filter;
}
 
Example 13
Source File: ApiGatewayApplication.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
@Bean
public FilterRegistrationBean<CorsFilter> simpleCorsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.setAllowedOrigins(Collections.singletonList("*"));
    config.setAllowedMethods(Collections.singletonList("*"));
    config.setAllowedHeaders(Collections.singletonList("*"));
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
}
 
Example 14
Source File: CommonCorsConfiguration.java    From tools with MIT License 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "corsFilter")
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.setAllowCredentials(commonCors.getAllowCredentials());
    corsConfiguration.setAllowedHeaders(Arrays.asList(commonCors.getAllowedHeaders()));
    corsConfiguration.setAllowedOrigins(Arrays.asList(commonCors.getAllowedOrigins()));
    corsConfiguration.setAllowedMethods(Arrays.asList(commonCors.getAllowedMethods()));
    source.registerCorsConfiguration(commonCors.getPath(), corsConfiguration);
    return new CorsFilter(source);
}
 
Example 15
Source File: RequestMappingHandlerMapping.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
	HandlerMethod handlerMethod = createHandlerMethod(handler, method);
	CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(), 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.getAllowedOrigins())) {
		config.setAllowedOrigins(Arrays.asList(CrossOrigin.DEFAULT_ORIGINS));
	}
	if (CollectionUtils.isEmpty(config.getAllowedMethods())) {
		for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) {
			config.addAllowedMethod(allowedMethod.name());
		}
	}
	if (CollectionUtils.isEmpty(config.getAllowedHeaders())) {
		config.setAllowedHeaders(Arrays.asList(CrossOrigin.DEFAULT_ALLOWED_HEADERS));
	}
	if (config.getAllowCredentials() == null) {
		config.setAllowCredentials(CrossOrigin.DEFAULT_ALLOW_CREDENTIALS);
	}
	if (config.getMaxAge() == null) {
		config.setMaxAge(CrossOrigin.DEFAULT_MAX_AGE);
	}
	return config;
}
 
Example 16
Source File: SecurityConfiguration.java    From skeleton-ws-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Defines a ConfigurationSource for CORS attributes.
 * 
 * @return A CorsConfigurationSource.
 */
@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(corsProperties.getAllowedOrigins());
    configuration.setAllowedMethods(corsProperties.getAllowedMethods());
    configuration.setAllowedHeaders(corsProperties.getAllowedHeaders());
    configuration.setAllowCredentials(corsProperties.getAllowCredentials());
    configuration.setExposedHeaders(corsProperties.getExposedHeaders());
    configuration.setMaxAge(corsProperties.getMaxAgeSeconds());

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration(corsProperties.getFilterRegistrationPath(), configuration);
    return source;
}
 
Example 17
Source File: SecurityManagedConfiguration.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty(prefix = "hawkbit.server.security.cors", name = "enabled", matchIfMissing = false)
CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration restCorsConfiguration = new CorsConfiguration();

    restCorsConfiguration.setAllowedOrigins(securityProperties.getCors().getAllowedOrigins());
    restCorsConfiguration.setAllowCredentials(true);
    restCorsConfiguration.setAllowedHeaders(securityProperties.getCors().getAllowedHeaders());
    restCorsConfiguration.setAllowedMethods(securityProperties.getCors().getAllowedMethods());

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/rest/**", restCorsConfiguration);

    return source;
}
 
Example 18
Source File: SecurityConfiguration.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.setAllowedOrigins(getPropertiesAsList("http.cors.allow-origin", "*"));
    config.setAllowedHeaders(getPropertiesAsList("http.cors.allow-headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With, If-Match, " + DEFAULT_CSRF_HEADER_NAME));
    config.setAllowedMethods(getPropertiesAsList("http.cors.allow-methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE"));
    config.setExposedHeaders(getPropertiesAsList("http.cors.exposed-headers", "ETag, " + DEFAULT_CSRF_HEADER_NAME));
    config.setMaxAge(environment.getProperty("http.cors.max-age", Long.class, 1728000L));

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);

    return source;
}
 
Example 19
Source File: CrustConfigurerAdapter.java    From Milkomeda with MIT License 5 votes vote down vote up
@Bean
protected CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Collections.singletonList("*"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "HEAD", "OPTION"));
    configuration.setAllowedHeaders(Collections.singletonList("*"));
    configuration.addExposedHeader(props.getRefreshTokenName());
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}
 
Example 20
Source File: SecurityConfigurer.java    From uexam with GNU Affero General Public License v3.0 5 votes vote down vote up
@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;
}