くらげになりたい。

くらげのようにふわふわ生きたい日曜プログラマなブログ。趣味の備忘録です。

Spring Boot/Spring Securityを使ってユーザ認証(独自のユーザテーブル)するときはパスワードエンコードしよう!

前の記事の続き。独自のユーザテーブルを使った時には、パスワードエンコードしよう!

wannabe-jellyfish.hatenablog.com

Before: パスワードエンコードなし

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  private UserInfoService userInfoService;

  (中略)

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userInfoService);
  }
}

After: パスワードエンコードあり

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  private UserInfoService userInfoService;

  (中略)

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userInfoService);
    authProvider.setPasswordEncoder(new BCryptPasswordEncoder());
    
    auth.authenticationProvider(authProvider);
  }
}

ちなみに、BCryptでエンコードする方法は以下の通り。

DBへ追加するときは、変換してから投入すればOK

String encodedPassword = BCrypt.hashpw(rawPassword, BCrypt.gensalt());

以上!

参考になる書籍

Spring Boot 2 プログラミング入門

Spring Boot 2 プログラミング入門

参考にしたサイト様