2016-02-10 4 views
10

アップデート: 1年以上後を振り返って、私は他の誰かを助ける更新の希望を与えています。SpringブートイネーブルグローバルCORSサポートの問題:POST、PUT、およびDELETEは機能していません。

通常のユーザーがブラウザで処理できるリクエストに対しては、CSRF保護を使用することをお勧めします。ブラウザ以外のクライアントで使用されているサービスだけを作成している場合は、CSRF保護を無効にすることをお勧めします。 私のアプリはAPIなのでブラウザで処理されるので、CSRFの使用は不可能です。

デフォルトではCSRFが有効になっており、次のコードを追加してCSRFリポ​​ジトリとCSRFトークンをhttpリクエストに追加するフィルタを追加する必要があります。私は2016年2月に戻って、私はグローバルにenabeingに取り組ん

を尋ね

private Filter csrfHeaderFilter() { 
    return new OncePerRequestFilter() { 

     @Override 
     protected void doFilterInternal(HttpServletRequest request, 
             HttpServletResponse response, 
             FilterChain filterChain) throws ServletException, IOException { 

      CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); 
      if (csrf != null) { 
       Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN"); 
       String token = csrf.getToken(); 
       if (cookie == null || token != null 
         && !token.equals(cookie.getValue())) { 

        // Token is being added to the XSRF-TOKEN cookie. 
        cookie = new Cookie("XSRF-TOKEN", token); 
        cookie.setPath("/"); 
        response.addCookie(cookie); 
       } 
      } 
      filterChain.doFilter(request, response); 
     } 
    }; 
} 


private CsrfTokenRepository csrfTokenRepository() { 
     HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); 
     repository.setHeaderName("X-XSRF-TOKEN"); 
     return repository; 
    } 

オリジナル質問:

@Override 
protected void configure(HttpSecurity http) throws Exception { 
     http 
      .authorizeRequests() 
       .antMatchers("/assets/**", "/templates/**", "/custom-fonts/**", "/api/profile/**", "/h2/**").permitAll() 
       .anyRequest().authenticated() 
       .and() 
      .formLogin() 
       .loginPage("/login") 
       .permitAll() 
       .and() 
      .logout() 
       .logoutSuccessUrl("/login?logout") 
       .permitAll() 
       .and() 
      .csrf().csrfTokenRepository(csrfTokenRepository()) 
       .and() 
      .addFilterAfter(csrfHeaderFilter(), SessionManagementFilter.class); // Register csrf filter. 
       } 

フィルタ& CsrfTokenリポジトリの一部(溶液がInvalid CSRF Token in POST requestここから来ています) Spring 4でのSpring起動RESTful APIのCORSサポート。

私は公式の春ブーツドク(https://spring.io/guides/gs/rest-service-cors/)を、次の午前と私のアプリケーションにこれを追加しました:

public class SomeApiApplication { 

    public static void main(String[] args) { 
     SpringApplication.run(SomeApiApplication.class, args); 
    } 


    //Enable Global CORS support for the application 
    @Bean 
    public WebMvcConfigurer corsConfigurer() { 
     return new WebMvcConfigurerAdapter() { 
      @Override 
      public void addCorsMappings(CorsRegistry registry) { 
       registry.addMapping("/**") 
         .allowedOrigins("http://localhost:8080") 
         .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD") 
         .allowedHeaders("header1", "header2") //What is this for? 
         .allowCredentials(true); 
      } 
     }; 
    } 
} 

のみ、HTTP呼び出しの残りのために、私は取得しています働いているGETなぜ私は得ることはありません「CORS要求が無効です」というエラーメッセージが表示されます。私はセットアップで何かを欠場しますか?私の設定が正しくない場合、GETはうまくいけません。私は非常に混乱しています。

+0

は、私がテストしPOSTMANを使用していますXML構成 – Abdelhak

+0

を投稿してください。私の要求ヘッダーについては、私はAuthorizationとContent-Typeを持っています。 CORSのヘッダーを追加する必要があるのだろうか? –

+0

@Abdelhak:私はSpring 4を使用しています。私のコードにはXMLを入れてはいけません。 –

答えて

2

私は同様の問題があり、問題を解決するためにコントローラの@CrossOriginを削除しなければならないことを理解しました。しかし、それがなぜ「無効なCORS要求」を引き起こしているのかを理解する。

4

私は同じ問題を抱えていました.GETが働いていました。 POSTはしませんでした。私はCORSドメインで答えを探しましたが、最終的にはCSRF保護によるものであることがわかりました。

@Configuration @EnableWebSecurity 
    public class SpringWebSecurityConfiguration extends WebSecurityConfigurerAdapter { 
     @Override 
     protected void configure(HttpSecurity http) throws Exception { 
      http 
       **.csrf().disable()** //TODO: for production, must be reconfigured in order to disable only in specific cases. This line was added because without it, HTTP POST requests did not work. 
       .authorizeRequests() 
        .antMatchers("/api/**").permitAll() 
        .anyRequest().authenticated() 
        .and() 
       .formLogin() 
        .loginPage("/login") 
        .permitAll() 
        .and() 
       .logout() 
        .permitAll(); 
     } 

あなたは何をやっている理解していることを確認してください:https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html

5

.allowedOrigins("*")allowedOrigins方法を変更しようとするセキュリティ設定で、I無効にCSRFの保護をそれを解決するために 。 Postmanは拡張機能で、別の "ホスト"で動作します。

しかし、あなたが影響を理解していることを確認してください:https://spring.io/understanding/CORS

関連する問題