LoginSignup
30
33

More than 5 years have passed since last update.

Spring Security 4を使ったらハマった

Last updated at Posted at 2016-01-14

Spring Security 4では、デフォルトでCSRFが有効になった。
認証しようとすると画面上に、

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

って出てハッ?ってなったけど、Stack OverflowやらSpring Security 3から4へのマイグレーションガイド見ていたら書いてあった。なので、自分は以下のような感じで回避(無効化)した(ちなみにSpring Bootです)。

SecurityConfig.java(抜粋)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login").permitAll().anyRequest().authenticated();
        // ★http.csrf().disable()でCSRFを無効 
        http.csrf().disable().formLogin().loginProcessingUrl("/auth").loginPage("/login").failureUrl("/login?error")
                .defaultSuccessUrl("/top", true).usernameParameter("userId").passwordParameter("password");
    }
}

トークンを送信する場合は、以下のページにあるような形でトークンを設定してあげれば大丈夫そう。
https://terasolunaorg.github.io/guideline/public_review/Security/CSRF.html

あとは、Spring Security 4では@EnableWebMvcSecurityは非推奨になっているので、代わりに@EnableWebSecurityを利用した。
https://docs.spring.io/spring-security/site/docs/current/reference/html/mvc.html

Spring Security 4のマイグレーションガイド
http://docs.spring.io/spring-security/site/migrate/current/3-to-4/html5/migrate-3-to-4-xml.html

ちなみに背景として、書籍「はじめてのSpring Boot」のSpring Securityをやっていて、本では基本的にSpring Boot 1.1.8.RELEASEを利用していて、この時のSpring Securityのバージョンは3.2.5.RELEASEなんだけど、何を血迷ったか最新のSpring Boot使いたいなぁと思い1.3.1.RELEASEを指定したらSpring Security 4になっていてこうなった。

30
33
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
33