# CORS

Spring Framework提供[CORS的一流支持](https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-cors)。CORS必须在 Spring 安全性之前进行处理，因为飞行前请求将不包含任何cookie（即`JSESSIONID`）。如果请求不包含任何cookie并且 Spring 安全性是第一位的，则该请求将确定用户未经过身份验证（因为在该请求中没有cookie）并拒绝它。

确保先处理CORS的最简单方法是使用`CorsFilter`。用户可以通过以下方式提供`CorsConfigurationSource`，将`CorsFilter`与 Spring 安全性集成在一起：

Java

```
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			// by default uses a Bean by the name of corsConfigurationSource
			.cors(withDefaults())
			...
	}

	@Bean
	CorsConfigurationSource corsConfigurationSource() {
		CorsConfiguration configuration = new CorsConfiguration();
		configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
		configuration.setAllowedMethods(Arrays.asList("GET","POST"));
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", configuration);
		return source;
	}
}
```

Kotlin

```
@EnableWebSecurity
open class WebSecurityConfig : WebSecurityConfigurerAdapter() {
    override fun configure(http: HttpSecurity) {
        http {
            // by default uses a Bean by the name of corsConfigurationSource
            cors { }
            // ...
        }
    }

    @Bean
    open fun corsConfigurationSource(): CorsConfigurationSource {
        val configuration = CorsConfiguration()
        configuration.allowedOrigins = listOf("https://example.com")
        configuration.allowedMethods = listOf("GET", "POST")
        val source = UrlBasedCorsConfigurationSource()
        source.registerCorsConfiguration("/**", configuration)
        return source
    }
}
```

或在XML中

```
<http>
	<cors configuration-source-ref="corsSource"/>
	...
</http>
<b:bean id="corsSource" class="org.springframework.web.cors.UrlBasedCorsConfigurationSource">
	...
</b:bean>
```

如果使用 Spring MVC的CORS支持，则可以省略指定`CorsConfigurationSource`，并且 Spring Security将利用提供给 Spring MVC的CORS配置。

Java

```
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			// if Spring MVC is on classpath and no CorsConfigurationSource is provided,
			// Spring Security will use CORS configuration provided to Spring MVC
			.cors(withDefaults())
			...
	}
}
```

Kotlin

```
@EnableWebSecurity
open class WebSecurityConfig : WebSecurityConfigurerAdapter() {
    override fun configure(http: HttpSecurity) {
        http {
            // if Spring MVC is on classpath and no CorsConfigurationSource is provided,
            // Spring Security will use CORS configuration provided to Spring MVC
            cors { }
            // ...
        }
    }
}
```

或在XML中

```
<http>
	<!-- Default to Spring MVC's CORS configuration -->
	<cors />
	...
</http>
```

[WebSocket](websocket.html)[JSP Taglib](jsp-taglibs.html)

