use of org.springframework.security.web.authentication.preauth.PreAuthenticatedCredentialsNotFoundException in project dhis2-core by dhis2.
the class TwoFactorAuthenticationProvider method authenticate.
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
log.debug(String.format("Login attempt: %s", auth.getName()));
String username = auth.getName();
User user = userService.getUserWithEagerFetchAuthorities(username);
if (user == null) {
throw new BadCredentialsException("Invalid username or password");
}
// Initialize all required properties of user credentials since these
// will become detached
user.getAllAuthorities();
if (user.isTwoFA() && auth.getDetails() instanceof TwoFactorWebAuthenticationDetails) {
TwoFactorWebAuthenticationDetails authDetails = (TwoFactorWebAuthenticationDetails) auth.getDetails();
if (authDetails == null) {
log.info("Missing authentication details in authentication request.");
throw new PreAuthenticatedCredentialsNotFoundException("Missing authentication details in authentication request.");
}
String ip = authDetails.getIp();
String code = StringUtils.deleteWhitespace(authDetails.getCode());
if (securityService.isLocked(username)) {
log.debug(String.format("Temporary lockout for user: %s and IP: %s", username, ip));
throw new LockedException(String.format("IP is temporarily locked: %s", ip));
}
if (!LongValidator.getInstance().isValid(code) || !SecurityUtils.verify(user, code)) {
log.debug(String.format("Two-factor authentication failure for user: %s", user.getUsername()));
throw new BadCredentialsException("Invalid verification code");
}
} else if (user.isTwoFA() && !(auth.getDetails() instanceof TwoFactorWebAuthenticationDetails)) {
throw new BadCredentialsException("Can't authenticate non form based login with 2FA enabled");
}
// -------------------------------------------------------------------------
// Delegate authentication downstream, using User as
// principal
// -------------------------------------------------------------------------
Authentication result = super.authenticate(auth);
// Put detached state of the user credentials into the session as user
// must not be updated during session execution
user = SerializationUtils.clone(user);
// Initialize cached authorities
user.isSuper();
user.getAllAuthorities();
return new UsernamePasswordAuthenticationToken(user, result.getCredentials(), result.getAuthorities());
}
Aggregations