アップデート: 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はうまくいけません。私は非常に混乱しています。
は、私がテストしPOSTMANを使用していますXML構成 – Abdelhak
を投稿してください。私の要求ヘッダーについては、私はAuthorizationとContent-Typeを持っています。 CORSのヘッダーを追加する必要があるのだろうか? –
@Abdelhak:私はSpring 4を使用しています。私のコードにはXMLを入れてはいけません。 –