3
0

More than 3 years have passed since last update.

Spring Security使用時に、Http://localhost:8080/h2-console で接続できない(CSRF対策)

Last updated at Posted at 2021-03-15

Spring Security使用時に、Http://localhost:8080/h2-console で接続できない場合、試したこと。

①まず、ログイン不要ページにh2-console/**を追加します。

ログインしていなくてもHttp://localhost:8080/h2-console/~ にアクセスできるように。

**はいずれかのファイル、という意味の正規表現
/webjars/** /css/** /login(ログイン画面) /signup(ユーザー登録画面)、などと一緒に直列で書く。(下は一例)

SecurityConfig.java
@Override
    protected void configure(HttpSecurity http) throws Exception {
        //ログイン不要ページの設定
        http.authorizeRequests().antMatchers("/webjars/**").permitAll().antMatchers("/css/**").permitAll()
                .antMatchers("/login").permitAll().antMatchers("/signup").permitAll().antMatchers("/h2-console/**")
                .permitAll().anyRequest().authenticated();
    }

②接続が拒否されないように下の一文を追加する。

SecurityConfig.java
@Override
    protected void configure(HttpSecurity http) throws Exception {

        //h2consoleを使用可能に(SpringSecurityを入れている場合consoleで接続を拒否される)
        http.headers().frameOptions().disable();
    }

③最後に、CSRF対策時に追加する項目。

理由:connectする時に、formを送信するため。CSRF対策では、トークン無しのformはログイン失敗とみなされる。なのでignoreさせます。
SecurityConfig.java
@Override
    protected void configure(HttpSecurity http) throws Exception {

        //h2-consoleのCSRF対策   
        http.csrf().ignoringAntMatchers("/h2-console/**");
    }

完成図

SecurityConfig.java
@Override
    protected void configure(HttpSecurity http) throws Exception {
        //ログイン不要ページの設定
        http.authorizeRequests().antMatchers("/webjars/**").permitAll().antMatchers("/css/**").permitAll()
                .antMatchers("/login").permitAll().antMatchers("/signup").permitAll().antMatchers("/h2-console/**")
                .permitAll().antMatchers("/admin","/userDetailAdmin/**").hasAuthority("ROLE_ADMIN").anyRequest().authenticated();
        //ログイン処理
        //ログイン処理のパス、ページの指定、ログイン失敗時の遷移先、
        //ログインページのID・パスワード、ログイン成功時の遷移先
        http.formLogin().loginProcessingUrl("/login").loginPage("/login").failureUrl("/login")
                .usernameParameter("userId").passwordParameter("password").defaultSuccessUrl("/home", true);
        //ログアウト処理
        http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutUrl("/logout")
                .logoutSuccessUrl("/login");
        //h2-consoleのCSRF対策
        http.csrf().ignoringAntMatchers("/h2-console/**");
        //h2consoleを使用可能(SpringSecurityを入れている場合consoleで接続を拒否される)
        http.headers().frameOptions().disable();
    }

追記:csrf対策はデフォルトでONになっているので、ignoreを使わず、http.csrf().disable();とするのもありです。

CSRF対策をOFFにします。
一般的にはそう出てきますw
でもCSRF対策実装したいよね、、ということなので、よろしくお願いします。

まとめ

埋め込み式で便利なh2-console、Spring Security上で動かすときは、適宜SecurityConfig.javaに書いて対応しよう、という記事でした。

ご精読ありがとうございました。

3
0
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
3
0