You may also use Spring Security when trying to implement authentication with Spring Boot. 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 you want to add other items for authentication.
is used to get the user, so we will take advantage of this and implement it additionally. This time, we will implement it by using
DaoAuthenticationProvider`. I refer to the article Check extra parameters with Spring Security.Add authenticationProvider to SecurityConfig. authenticationProvider sets ʻAuthenticationProviderImpl` which is implemented independently described later. Also, set 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 that is implemented independently. I've added a status column to the table to authenticate users who aren't ʻactive`.
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() {}
}
Recommended Posts