[Java] Add your own authentication item with Spring Security

1 minute read

Overview

When you try to implement authentication with Spring Boot, I think that you may also use Spring Security. Spring Security has a mechanism to automatically authenticate if you set items at login, but basically it authenticates with a set of user name and password. I will write what to do if I want to add an item for authentication other than that.

Assumptions, etc.

Implementation sample

Add authenticationProvider to SecurityConfig. authenticationProvider sets AuthenticationProviderImpl which is implemented independently described later. Also, configure authenticationProvider in configureGlobal.

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 to implement by yourself. The status column is added to the table and users who are not active are authenticated as 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;

    // additional conditions
    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 () {}
}

Other references