質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.47%
Spring Security

Spring Securityは、Springのサブプロジェクトの一つでWebアプリケーションに必要な機能を追加します。正規ユーザーであるかを確認するための「認証機能」と、ユーザーのアクセスを制御する「認可機能」を簡単に追加することが可能です。

Spring

Spring Framework は、Javaプラットフォーム向けのオープンソースアプリケーションフレームワークです。 Java Platform上に、 Web ベースのアプリケーションを設計するための拡張機能が数多く用意されています。

Q&A

解決済

1回答

213閲覧

Spring Securityを利用したRestAPIでCSRFトークンを利用したい

houpuw

総合スコア2

Spring Security

Spring Securityは、Springのサブプロジェクトの一つでWebアプリケーションに必要な機能を追加します。正規ユーザーであるかを確認するための「認証機能」と、ユーザーのアクセスを制御する「認可機能」を簡単に追加することが可能です。

Spring

Spring Framework は、Javaプラットフォーム向けのオープンソースアプリケーションフレームワークです。 Java Platform上に、 Web ベースのアプリケーションを設計するための拡張機能が数多く用意されています。

0グッド

0クリップ

投稿2024/03/23 02:42

編集2024/03/23 05:55

実現したいこと

以下のサイトを参考にSpring SecurityでCSRFトークンを利用したRestAPIの開発を行っています。
https://volkruss.com/posts/p3398/
最終的には上記サイトと同様にCSRFトークンを付与したPOST送信をPostmanから行うとStatus200でPOSTメソッドが正常終了することを目指したいです。

発生している問題・分からないこと

ヘッダーにX-XSRF-TOKENの値を付与してPOST送信を行っても403エラーが返却されreturn値を取得することができません。

・GET通信でXSRF-TOKENを取得
イメージ説明

・ヘッダーにX-XSRF-TOKENを付与してPOST通信すると403エラー
イメージ説明

403エラーが発生している原因及び対処法をご教示いただきたいです。

エラーメッセージ

error

1{ 2 "timestamp": "2024-03-23T02:15:12.423+00:00", 3 "status": 403, 4 "error": "Forbidden", 5 "message": "Forbidden", 6 "path": "/post" 7}

追記
以下のエラーがコンソールに出力されていました。
「Invalid CSRF token found」とあるのでトークンは渡せているが無効なトークンということでしょうか。
Postmanでのトークンの受け渡し方法などに不適な部分がありましたらご教示お願い致します。

error

1o.s.security.web.FilterChainProxy Securing POST /post 2o.s.security.web.csrf.CsrfFilter Invalid CSRF token found for http://localhost:8080/post 3o.s.s.w.access.AccessDeniedHandlerImpl Responding with 403 status code 4o.s.security.web.FilterChainProxy Securing POST /error 5o.s.security.web.FilterChainProxy Secured POST /error 6o.s.s.w.a.AnonymousAuthenticationFilter Set SecurityContextHolder to anonymous SecurityContext

該当のソースコード

SecurityConfig.java

1package com.example.demo.login; 2 3import java.util.Arrays; 4 5import org.springframework.context.annotation.Bean; 6import org.springframework.context.annotation.Configuration; 7import org.springframework.security.config.annotation.web.builders.HttpSecurity; 8import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 9import org.springframework.security.web.SecurityFilterChain; 10import org.springframework.security.web.csrf.CookieCsrfTokenRepository; 11import org.springframework.web.cors.CorsConfiguration; 12import org.springframework.web.cors.CorsConfigurationSource; 13import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 14 15@Configuration 16@EnableWebSecurity 17public class SecurityConfig { 18 @Bean 19 public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { 20 21 http.csrf((csrf) -> csrf 22 .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())); 23 24 http.authorizeHttpRequests(authorize -> { 25 authorize 26 .requestMatchers("/**").permitAll(); 27 }); 28 29 http.cors(cors -> cors.configurationSource(corsConfigurationSource())); 30 31 return http.build(); 32 } 33 34 //CORSの設定 35 @Bean 36 public CorsConfigurationSource corsConfigurationSource() { 37 CorsConfiguration cors = new CorsConfiguration(); 38 cors.setAllowedOrigins(Arrays.asList("http://localhost:4200")); 39 cors.setAllowedMethods(Arrays.asList("GET", "POST")); 40 cors.setAllowedHeaders(Arrays.asList("*")); 41 // cookieなどの情報を許可 42 cors.setAllowCredentials(true); 43 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 44 source.registerCorsConfiguration("/**",cors); 45 return source; 46 } 47}

testController.java

1package com.example.demo.controller; 2 3import org.springframework.web.bind.annotation.GetMapping; 4import org.springframework.web.bind.annotation.PostMapping; 5import org.springframework.web.bind.annotation.RestController; 6 7@RestController 8public class testController { 9 @GetMapping("/get") 10 public String doGet() { 11 return "sample GET is done"; 12 } 13 14 @PostMapping("/post") 15 public String doPost() { 16 return "sample POST is done"; 17 } 18}

試したこと・調べたこと

  • teratailやGoogle等で検索した
  • ソースコードを自分なりに変更した
  • 知人に聞いた
  • その他
上記の詳細・結果

・get,post通信を行うために自作のcontrollerを作成しました。
get通信は正常に行えますがpost通信で403エラーが発生しました。

・SecurityConfig.javaに以下のコードを追加してCSRF対策無効化すると正常にPOST送信が行えました。
http.csrf().disable();

補足

setAllowedOriginsの値は参考サイトでは
(Arrays.asList("http://localhost:3000"));
となっていますが、後々AngularからPOST通信を行いたいため
(Arrays.asList("http://localhost:4200"));
に変更しています。
3000番も試しましたが結果は同様でした。

spring-boot-starter-parent:3.2.4
Spring Security Version: 6.2.3
Eclipse IDE for Java Developers Version: 2023-12 (4.30.0)
Postman for Windows:10.24.7

よろしくお願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

以下のサイトを参考にSecurityFilterChainの内容を修正しました。
https://www.linkedin.com/pulse/solving-invalid-csrf-token-found-error-spring-security-oyeleye

http.csrf((csrf) -> csrf .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
http.csrf((csrf) -> csrf .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()));

投稿2024/03/23 06:26

編集2024/03/23 06:26
houpuw

総合スコア2

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.47%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問