AuthenticationManagerBuilderについて

今回は、AuthenticationManagerBuilderについてメモ書きです。

AuthenticationManagerBuilderとは

ログインのためにはSecurityConfigクラスに「AuthenticationManagerBuilder」を挿入して認証に対する処理を行わなければなりません。「AuthenticationManagerBuilder」は認証に利用する様々な設定を生成することができます。

AuthenticationManagerBuilderは認証マネージャーを生成するビルダーです。

メモリを利用して認証

@Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
 
        authenticationManagerBuilder.inMemoryAuthentication()
                .withUser("admin")
                .password("{noop}1234")
                .roles("ADMIN");
    }
  • IDはadminでパスワードは1234でログインが可能になります。

userDetailsServiceを利用して認証

@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder)
throws Exception {
authenticationManagerBuilder
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());
}
  • UserDetailsServiceをインプリメントしたクラス(customUserDetailsService)を利用しています。
Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    UserRepository userRepository;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String email)
            throws UsernameNotFoundException {

        User user = userRepository.findByEmail(email)
                .orElseThrow(() ->
                        new UsernameNotFoundException("User not found with email : " + email)
                );

        return UserPrincipal.create(user);

    }
}
  • loadUserByUsernameをオーバーライドして認証処理を行っています。

終わりに

勉強している内容のメモ書きなので、間違っているところがあるかもしれません。

コメントを残す