Spring Security 5のデフォルトパスワードエンコーダ

Spring Security 5のデフォルトのパスワードエンコーダー

1. 概要

Spring Security 4では、インメモリ認証を使用してパスワードをプレーンテキストで保存することができました。

バージョン5のパスワード管理プロセスの大幅な見直しにより、パスワードのエンコードおよびデコードのためのより安全なデフォルトメカニズムが導入されました。 これは、Springアプリケーションがパスワードをプレーンテキストで保存している場合、Spring Security 5にアップグレードすると問題が発生する可能性があることを意味します。

この短いチュートリアルでは、これらの潜在的な問題の1つについて説明し、問題の解決策を示します。

2. Spring Security 4

まず、単純なメモリ内認証を提供する標準のセキュリティ構成を示します(Spring 4で有効)。

@Configuration
public class InMemoryAuthWebSecurityConfigurer
  extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
      throws Exception {
        auth.inMemoryAuthentication()
          .withUser("spring")
          .password("secret")
          .roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .antMatchers("/private/**")
          .authenticated()
          .antMatchers("/public/**")
          .permitAll()
          .and()
          .httpBasic();
    }
}

この構成は、すべての/private/マップメソッドの認証と/public/.の下のすべてのパブリックアクセスを定義します

Spring Security 5で同じ構成を使用すると、次のエラーが発生します。

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"

このエラーは、指定されたパスワードがcouldn’t be decoded since no password encoder was configured for our in-memory authenticationであることを示しています。

3. Spring Security 5

PasswordEncoderFactoriesクラスでDelegatingPasswordEncoder を定義することで、このエラーを修正できます。

このエンコーダーを使用して、AuthenticationManagerBuilder:でユーザーを構成します

@Configuration
public class InMemoryAuthWebSecurityConfigurer
  extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
      throws Exception {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        auth.inMemoryAuthentication()
          .withUser("spring")
          .password(encoder.encode("secret"))
          .roles("USER");
    }
}

現在、この構成では、BCryptを使用してメモリ内のパスワードを次の形式で保存しています。

{bcrypt}$2a$10$MF7hYnWLeLT66gNccBgxaONZHbrSMjlUofkp50sSpBw2PJjUqU.zS

独自のパスワードエンコーダーのセットを定義することもできますが、PasswordEncoderFactoriesで提供されるdefault encodersを使用することをお勧めします。

3.1. 既存のパスワードの移行

次の方法で、既存のパスワードを推奨のSpring Security 5標準に更新できます。

  • エンコードされた値でのプレーンテキストの保存パスワードの更新:

String encoded = new BCryptPasswordEncoder().encode(plainTextPassword);
  • ハッシュされた保存パスワードに既知のエンコーダー識別子を接頭辞として付加する:

{bcrypt}$2a$10$MF7hYnWLeLT66gNccBgxaONZHbrSMjlUofkp50sSpBw2PJjUqU.zS
{sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0
  • 保管されたパスワードのエンコード機構が不明な場合に、ユーザーにパスワードの更新を要求する

4. 結論

この簡単な例では、新しいパスワードストレージメカニズムを使用して、Spring 4の有効なメモリ内認証構成をSpring 5に更新しました。

いつものように、ソースコードはGitHub projectにあります。