必要なCSRFトークンが見つかりません。セッションの有効期限が切れていますか?403 質問する

必要なCSRFトークンが見つかりません。セッションの有効期限が切れていますか?403 質問する

私は、mkyong の例を使用してテスト Spring Security アプリケーションを作成しようとしています。

Spring Security: 4.0.0.RC1
Spring: 4.1.4.RELEASE

次のセキュリティ構成があります:

<http auto-config="true">
    <intercept-url pattern="/admin**" 
                    access="hasRole('ADMIN')"/>
    <form-login authentication-failure-url="/?auth_error" 
                        username-parameter="user" 
                        password-parameter="password" 
                        login-page="/"
                        default-target-url="/?OK"/>
<!-- <csrf/> -->
</http>

<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="mkyong" password="123456" authorities="ADMIN" />
        </user-service>
    </authentication-provider>
</authentication-manager>

ログインページ:

<html>
<body>
<form method="POST">
    <label for="user">User: </label>
    <input type="text" id="user" name="user" /> </br>
    <label for="password">Password: </label>
    <input type="text" name="password" id="password" /> </br>
    <input type="submit" /> 
</form>
</body>
</html>

ログインしようとすると、403 エラー ページが表示されます。

Invalid CSRF Token 'null' was found on the request parameter 
'_csrf' or header 'X-CSRF-TOKEN'.

説明:

Access to the specified resource (Invalid CSRF Token 'null' was
found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.) has been 
forbidden.

何が問題なのですか、どうすれば修正できますか?csrf設定にコメントしましたが、エラー メッセージは に関係していますcsrf

ベストアンサー1

私も同じ問題を抱えていました。thymeleaf と Spring boot を使用していますが、フォームにデータを投稿しようとすると CSRF トークンの問題が発生しました。

これが私の実用的な解決策です:

  1. 次の隠し入力を追加します。

    <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />

  2. WebSecurityConfig( を拡張)にWebSecurityConfigurerAdapter、メソッドを追加します。

    private CsrfTokenRepository csrfTokenRepository() 
    { 
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); 
        repository.setSessionAttributeName("_csrf");
        return repository; 
    }
    

    メソッドにコードを追加しますconfigure():

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

私はこの問題に多くの時間を費やしました。同じ問題を抱えている人の助けになれば幸いです。

おすすめ記事