2016-04-23 31 views
7

CORSフィルタをSpringブートWebアプリケーションに追加する必要があります。私は私のAPIにアクセスしようとしている私は、次のエラーを受信したときに今SpringブートCORSフィルタ - CORSプリフライトチャネルが成功しませんでした

@Configuration 
@EnableWebMvc 
public class WebMvcConfig extends WebMvcConfigurerAdapter { 

    @Override 
    public void addCorsMappings(CorsRegistry registry) { 
     // @formatter:off 
     registry 
      .addMapping("/**") 
      .allowedOrigins(CrossOrigin.DEFAULT_ORIGINS) 
      .allowedHeaders(CrossOrigin.DEFAULT_ALLOWED_HEADERS) 
      .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") 
      .maxAge(3600L); 
     // @formatter:on 
    } 

... 

} 

:以下の文書で説明するように

私はこれが私のconfigですhttp://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html

CORSのマッピングを追加した

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/api/v1.0/user. (Reason: CORS preflight channel did not succeed). 

これはFFコンソールからのスクリーンショットである。

enter image description here

この問題を回避するために、私は間違っていますか、CORSヘッダーを正しく設定する方法を教えてください。

答えて

20

は、私は新しいCORSフィルター作成することで、この問題を修正しました:

@Component 
public class CorsFilter extends OncePerRequestFilter { 

    @Override 
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { 
     response.setHeader("Access-Control-Allow-Origin", "*"); 
     response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); 
     response.setHeader("Access-Control-Max-Age", "3600"); 
     response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, xsrf-token"); 
     response.addHeader("Access-Control-Expose-Headers", "xsrf-token"); 
     if ("OPTIONS".equals(request.getMethod())) { 
      response.setStatus(HttpServletResponse.SC_OK); 
     } else { 
      filterChain.doFilter(request, response); 
     } 
    } 
} 

をしてsecurtyためにこれを追加した構成:

.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class) 

UPDATED - 私はに切り替え、今日より近代的な方法:

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 

     http 
      .cors() 
     .and() 

     ... 
    } 

    @Bean 
    public CorsConfigurationSource corsConfigurationSource() { 
     CorsConfiguration configuration = new CorsConfiguration(); 
     configuration.setAllowedOrigins(Arrays.asList("*")); 
     configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")); 
     configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token")); 
     configuration.setExposedHeaders(Arrays.asList("x-auth-token")); 
     UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
     source.registerCorsConfiguration("/**", configuration); 
     return source; 
    } 

} 
+1

適切なRESTful APIをサポートしたい場合は、そこにPUT動詞も追加すべきでしょうか? –

0

飛行前のOPTIONS要求を適切に処理する必要がありますが、クロスサイトリソース要求が機能するには十分ではありません。

満足しているヘッダーが返された後、同じURLへのその後のリクエストに対するすべての応答にも、必要な "Access-Control-Allow-Origin"ヘッダーが必要です。そうしないと、ブラウザはそれらを飲み込み、デバッガウィンドウにも表示されません。 https://stackoverflow.com/a/11951532/5649869

+0

最初に、許可されたメソッドで必要なhttpメソッドだけを残します。次にcurl 'curl -H" Origin:http://127.0.0.1 "--verbose http:// 127.0.0.1/api/v1.0/user'を使ってrawリクエストを試してください。応答では、Access-Control-Allowed- *ヘッダーが必要です。最後に、AllowedOriginにホスト(http://127.0.0.1またはsmth。else)を指定しようとします。 –

+0

私は 'allowedHeaders(" xsrf-token ")を試しました。exposedHeaders( "xsrf-token") 'でもまだ動作しません。私はこのようなものが必要だと思う - '(" OPTIONS ".equals(request.getMethod())){ \t \t \t response.setStatus(HttpServletResponse.SC_OK); \t \t} 'このロジックを' CorsRegistry registry'に追加する方法がわかりません – alexanoid

2

CORSにスプリングデータ休止を働かせるのと同じ問題があったのですが、これは私が使用したフィルタコードでした。その価値は、以下の組み合わせのソリューションは、私のために働いていた何のため

/** 
* Until url{https://jira.spring.io/browse/DATAREST-573} is fixed 
* 
* @return 
*/ 
@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("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); 
} 
1

:RestControllerクラスの

1.

@Configuration 
public class CorsConfiguration { 

//This can be used in combination with @CrossOrigin on the controller & method. 

    @Bean 
    public WebMvcConfigurer corsConfigurer() { 
     return new WebMvcConfigurerAdapter() { 
      @Override 
      public void addCorsMappings(CorsRegistry registry) { 
       registry.addMapping("/**") 
         .allowedMethods("HEAD","OPTIONS") 
         .allowedHeaders("Origin", "X-Requested-With", "Content-Type", "Accept"); 
      } 
     }; 
    } 
} 

2. @CrossOrigin@CrossOriginは、@RequestMapping注釈とその中のHTTPメソッドを読み取ります。要求の残りの部分はCORSエラーで拒否されます。

しかし、あなたのプロジェクトで春のセキュリティを使用する場合は、上記の解決策で不運になります。

私は春のブートバージョン1.5.4.RELEASEを使用しています。

関連する問題