舞台裏

Qiita が表でこっちが裏。こっそりやっていく。

19. CORS

Spring Framework provides first class support for CORS.

Spring Framework は CORS をサポートするクラスを提供します。

CORS must be processed before Spring Security because the pre-flight request will not contain any cookies (i.e. the JSESSIONID).

CORS は、 Spring Security の前に処理されなければなりません。なぜなら、 pre-flight リクエストは cookie をまったく含んでいないためです。

If the request does not contain any cookies and Spring Security is first, the request will determine the user is not authenticated (since there are no cookies in the request) and reject it.

もし、リクエストが cookie を含んでいない状態で Spring Security が最初に処理をすると、リクエストはユーザーが未認証であると結論づけられ(リクエストに cookie が無いので)、リクエストが拒否されます。

The easiest way to ensure that CORS is handled first is to use the CorsFilter.

CORS が最初に処理されるようにすることを確実にするための最も簡単な手段は、 CorsFilter を使うことです。

Users can integrate the CorsFilter with Spring Security by providing a CorsConfigurationSource using the following:

ユーザは、 Spring Security が提供する CorsConfigurationSource を次のように使うことで、 CorsFilter を統合できます。

@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().and()
            ...
    }

    @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;
    }
}

or in XML

もしくは xml なら

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

If you are using Spring MVC’s CORS support, you can omit specifying the CorsConfigurationSource and Spring Security will leverage the CORS configuration provided to Spring MVC.

もしあなたが Spring MVC の CORS サポートを使っているなら、あなたは CorsConfigurationSource の指定を省略でし、 Spring MVC が提供する CORS の設定を利用するようにできます。

@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().and()
            ...
    }
}

or in XML

もしくは XML なら

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