3
7

More than 3 years have passed since last update.

Spring Securityで独自の認証項目を追加する

Posted at

概要

Spring Bootで認証を実装しようとする際に、Spring Securityを使うこともあると思います。
Spring Securityではログイン時に項目を設定すれば自動で認証する仕組みがあるのですが、基本的にはユーザ名とパスワードのセットで認証を行います。それ以外に認証用の項目を追加したい場合はどうすればいいのか、書いてみます。

前提など

実装サンプル

SecurityConfigに、authenticationProviderを追加します。authenticationProviderは後述の独自に実装したAuthenticationProviderImplを設定します。
また、configureGlobalにてauthenticationProviderを設定します。

SecurityConfig.java
  @Autowired
  private AuthenticationProviderImpl authenticationProvider;

  @Autowired
  public void configureGlobal(
    AuthenticationManagerBuilder auth,
    @Qualifier("userService") UserDetailsService userDetailsService,
    PasswordEncoder passwordEncoder) throws Exception {

    authenticationProvider.setUserDetailsService(userDetailsService);
    authenticationProvider.setPasswordEncoder(passwordEncoder);
    auth.eraseCredentials(true)
      .authenticationProvider(authenticationProvider);
  }

独自で実装するauthenticationProvider。テーブルにstatus列を追加して、activeではないユーザは認証NGとしています。

AuthenticationProviderImpl.java
@Component
public class AuthenticationProviderImpl extends DaoAuthenticationProvider {
  @Override
  protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    super.additionalAuthenticationChecks(userDetails, authentication);
    User user = (User) userDetails;

    // 追加の条件
    if (!user.getStatus().equals("active")) {
      throw new AccountStatusNotActiveException("Status is not active");
    }
  }

  public static class AccountStatusNotActiveException extends AuthenticationException {
    public AccountStatusNotActiveException(String message) {
      super(message);
    }
  }

  @Override
  protected void doAfterPropertiesSet() {}
}

その他参考

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7