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:id "null"に対応するPasswordEncoderがない ……
このエラーは、メモリ内認証用にパスワードエンコーダが設定されていないため、指定されたパスワードをデコードできなかったことを示しています。
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
独自のパスワードエンコーダを定義することはできますが、https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/crypto/factory/PasswordEncoderFactoriesに従うことをお勧めします PasswordEncoderFactories で提供されている.html[デフォルトのエンコーダ]。
3.1. 既存のパスワードの移行
以下の方法で、既存のパスワードをSpring Security 5の推奨標準に更新することができます。
プレーンテキストで保存されているパスワードを、その値をエンコードして更新する。
String encoded = new BCryptPasswordEncoder().encode(plainTextPassword);
-
プレフィックスハッシュは、保存されているパスワードを既知のエンコーダ識別子でハッシュします。
{bcrypt}$2a$10$MF7hYnWLeLT66gNccBgxaONZHbrSMjlUofkp50sSpBw2PJjUqU.zS
{sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0
エンコーディングメカニズムが有効になっている場合は、パスワードの更新をユーザーに要求します。
保存されたパスワードが不明です
4.まとめ
この簡単な例では、新しいパスワード保存メカニズムを使用して、有効なSpring 4のメモリ内認証設定をSpring 5に更新しました。
いつものように、ソースコードはhttps://github.com/eugenp/tutorials/tree/master/spring-5-security/src/main/java/com/baeldung/inmemory[GitHub project]にあります。