Spring MVCでRest Controllerを使用し、Spring Securityを導入している場合、POSTリクエストを送信する際にCSRFトークンが必要っぽい。調べた限りでは、PUT/PATCH/DELETEも(GET除く)
1-1. Spring Securityの設定をjavaのファイルで行う場合
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated();
}
}
1-2. Spring Securityの設定をxmlで行う場合
Spring SecurityのXML設定ファイル(通常はsecurity-context.xmlなど)を用意します。CSRF保護を有効にするためには、以下のように設定します。
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<http>
<csrf />
<intercept-url pattern="/public/**" access="permitAll" />
<intercept-url pattern="/**" access="isAuthenticated()" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user" password="{noop}password" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
2. CSRFトークンの取得
CSRFトークンを取得するには、まずGETリクエストを送信し、レスポンスからCSRFトークンを取得します。通常、CSRFトークンはレスポンスヘッダまたはCookieに含まれます。
Postmanでの手順
GETリクエストの送信
URLに対してGETリクエストを送信します。例えば、http://localhost:8080/your-endpoint。
レスポンスヘッダからCSRFトークンを取得
レスポンスヘッダにX-CSRF-TOKENというヘッダが含まれている場合、その値がCSRFトークンです。
3. POSTリクエストにCSRFトークンを付与
取得したCSRFトークンを使って、POSTリクエストを送信します。
Postmanでの手順
新しいリクエストを作成
リクエストタイプをPOSTに設定し、適切なURLを入力します。
ヘッダにCSRFトークンを追加
Headersタブで、X-CSRF-TOKENという名前のヘッダを追加し、その値として取得したCSRFトークンを入力します。
必要なボディデータを入力
Bodyタブで、必要なデータを入力します。
以下は、Postmanでの具体的な設定例です。
GETリクエスト
URL: http://localhost:8080/your-endpoint
Method: GET
レスポンスヘッダ
Set-Cookie: XSRF-TOKEN=your-csrf-token; Path=/
POSTリクエスト
URL: http://localhost:8080/your-endpoint
Method: POST
Headers:
X-CSRF-TOKEN: your-csrf-token
Body:
raw (選択) → JSON (選択)
{ "key": "value" }
4. Postmanスクリプトを使った自動化
Postmanではスクリプトを使ってCSRFトークンの取得と設定を自動化することもできます。
Pre-request Script
pm.sendRequest('http://localhost:8080/your-endpoint', function (err, res) {
var csrfToken = res.headers.get('X-CSRF-TOKEN');
pm.globals.set('csrfToken', csrfToken);
});
ヘッダの設定
Key: X-CSRF-TOKEN
Value: {{csrfToken}}
これで、GETリクエストで取得したCSRFトークンを自動的にPOSTリクエストに付与することができます。
以上の手順で、Spring Securityを使用したSpring MVCアプリケーションに対して、PostmanでCSRFトークンを付与したPOSTリクエストをテストできます。