SpringBootのセキュリティ設定について説明していきます。
サンプルソース
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// メモリ上にユーザー情報を管理する
auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("password")).roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// すべてのリクエストに認証を要求する
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
// 平文のパスワードをハッシュ化して保存する
return new BCryptPasswordEncoder();
}
}
クラス設定
- クラスに@EnableWebSecurityを付与する
- WebSecurityConfigurerAdapterを継承する
ユーザー情報設定
configure(AuthenticationManagerBuilder auth)をオーバーライドします。こちらは、ユーザーの認証方式を決定するメソッドになります。
・inMemoryAuthentication()
メモリ上にユーザー情報を管理する
・password(passwordEncoder().encode(“password”))
平文のパスワードをハッシュ化して保存する
・roles
権限を設定する。
認証設定
configure(HttpSecurity http)をオーバーライドします。こちらは、Webアプリケーションのリソースにアクセスする際のセキュリティ方式を制御するメソッドになります。
・anyRequest()
すべてのリクエストに
・authenticated()
認証を要求する
・httpBasic()
ログインを要求する
パスワード設定
passwordEncoder()メソッドを作成します。@Beanを付与して、依存性注入を行い、あらゆる場所からメソッドを呼べるようにします。
・BCryptPasswordEncoder()
平文のパスワードをハッシュ化して保存する
設定は以上になります。
コメント