use of javax.security.auth.login.AccountLockedException in project sling by apache.
the class SlingAuthenticator method handleLoginFailure.
private boolean handleLoginFailure(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationInfo authInfo, final Exception reason) {
String user = authInfo.getUser();
boolean processRequest = false;
if (reason.getClass().getName().contains("TooManySessionsException")) {
// to many users, send a 503 Service Unavailable
log.info("handleLoginFailure: Too many sessions for {}: {}", user, reason.getMessage());
try {
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "SlingAuthenticator: Too Many Users");
} catch (IOException ioe) {
log.error("handleLoginFailure: Cannot send status 503 to client", ioe);
}
} else if (reason instanceof LoginException) {
log.info("handleLoginFailure: Unable to authenticate {}: {}", user, reason.getMessage());
if (isAnonAllowed(request) && !expectAuthenticationHandler(request) && !AuthUtil.isValidateRequest(request)) {
log.debug("handleLoginFailure: LoginException on an anonymous resource, fallback to getAnonymousResolver");
processRequest = getAnonymousResolver(request, response, new AuthenticationInfo(null));
} else {
// request authentication information and send 403 (Forbidden)
// if no handler can request authentication information.
AuthenticationHandler.FAILURE_REASON_CODES code = AuthenticationHandler.FAILURE_REASON_CODES.INVALID_LOGIN;
String message = "User name and password do not match";
if (reason.getCause() instanceof CredentialExpiredException) {
// force failure attribute to be set so handlers can
// react to this special circumstance
Object creds = authInfo.get("user.jcr.credentials");
if (creds instanceof SimpleCredentials && ((SimpleCredentials) creds).getAttribute("PasswordHistoryException") != null) {
code = AuthenticationHandler.FAILURE_REASON_CODES.PASSWORD_EXPIRED_AND_NEW_PASSWORD_IN_HISTORY;
message = "Password expired and new password found in password history";
} else {
code = AuthenticationHandler.FAILURE_REASON_CODES.PASSWORD_EXPIRED;
message = "Password expired";
}
} else if (reason.getCause() instanceof AccountLockedException) {
code = AuthenticationHandler.FAILURE_REASON_CODES.ACCOUNT_LOCKED;
message = "Account is locked";
} else if (reason.getCause() instanceof AccountNotFoundException) {
code = AuthenticationHandler.FAILURE_REASON_CODES.ACCOUNT_NOT_FOUND;
message = "Account was not found";
}
// preset a reason for the login failure
request.setAttribute(AuthenticationHandler.FAILURE_REASON_CODE, code);
ensureAttribute(request, AuthenticationHandler.FAILURE_REASON, message);
doLogin(request, response);
}
} else {
// general problem, send a 500 Internal Server Error
log.error("handleLoginFailure: Unable to authenticate " + user, reason);
try {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "SlingAuthenticator: data access error, reason=" + reason.getClass().getSimpleName());
} catch (IOException ioe) {
log.error("handleLoginFailure: Cannot send status 500 to client", ioe);
}
}
return processRequest;
}
use of javax.security.auth.login.AccountLockedException in project kylo by Teradata.
the class KyloRestLoginModule method doLogin.
@Override
protected boolean doLogin() throws Exception {
final LoginJerseyClientConfig userConfig = createClientConfig(true);
final User user;
try {
user = retrieveUser(userConfig);
} catch (final NotAuthorizedException e) {
log.debug("Received unauthorized response from Login API for user: {}", userConfig.getUsername());
throw new CredentialException("The username and password combination do not match.");
} catch (final ProcessingException e) {
log.error("Failed to process response from Login API for user: {}", userConfig.getUsername(), e);
throw new FailedLoginException("The login service is unavailable.");
} catch (final WebApplicationException e) {
log.error("Received unexpected response from Login API for user: {}", userConfig.getUsername(), e);
throw new FailedLoginException("The login service is unavailable.");
}
// Parse response
if (user == null) {
log.debug("No account exists with the name: {}", userConfig.getUsername());
throw new AccountNotFoundException("No account exists with the name: " + userConfig.getUsername());
} else if (!user.isEnabled()) {
log.debug("User from Login API is disabled: {}", userConfig.getUsername());
throw new AccountLockedException("The account \"" + userConfig.getUsername() + "\" is currently disabled");
}
addNewUserPrincipal(user.getSystemName());
user.getGroups().forEach(this::addNewGroupPrincipal);
return true;
}
use of javax.security.auth.login.AccountLockedException in project kylo by Teradata.
the class KyloLoginModule method doLogin.
@Override
protected boolean doLogin() throws Exception {
// Get username and password
final NameCallback nameCallback = new NameCallback("Username: ");
final PasswordCallback passwordCallback = new PasswordCallback("Password: ", false);
if (requirePassword) {
handle(nameCallback, passwordCallback);
} else {
handle(nameCallback);
}
// Authenticate user
metadata.read(() -> {
Optional<User> user = userProvider.findUserBySystemName(nameCallback.getName());
if (user.isPresent()) {
if (!user.get().isEnabled()) {
throw new AccountLockedException("The account \"" + nameCallback.getName() + "\" is currently disabled");
} else if (requirePassword && !passwordEncoder.matches(new String(passwordCallback.getPassword()), user.get().getPassword())) {
throw new CredentialException("The username and/or password combination do not match");
}
addPrincipal(user.get().getPrincipal());
addAllPrincipals(user.get().getAllGroupPrincipals());
} else {
throw new AccountNotFoundException("No account exists with name name \"" + nameCallback.getName() + "\"");
}
}, MetadataAccess.SERVICE);
return true;
}
use of javax.security.auth.login.AccountLockedException in project cas by apereo.
the class AccepttoMultifactorAuthenticationHandler method doAuthentication.
@Override
protected AuthenticationHandlerExecutionResult doAuthentication(final Credential credential) throws GeneralSecurityException {
try {
val url = StringUtils.appendIfMissing(accepttoProperties.getApiUrl(), "/") + "check";
val tokenCredential = (AccepttoMultifactorTokenCredential) credential;
LOGGER.debug("Received token [{}]", tokenCredential.getId());
val authentication = WebUtils.getInProgressAuthentication();
val attributes = authentication.getPrincipal().getAttributes();
val email = CollectionUtils.firstElement(attributes.get(accepttoProperties.getEmailAttribute())).map(Object::toString).orElseThrow(() -> new IllegalArgumentException("Unable to determine email address"));
LOGGER.debug("Email determined from attribute [{}] is [{}]", accepttoProperties.getEmailAttribute(), email);
val parameters = CollectionUtils.<String, Object>wrap("uid", accepttoProperties.getApplicationId(), "secret", accepttoProperties.getSecret(), "email", email, "channel", tokenCredential.getId());
HttpResponse response = null;
try {
val exec = HttpUtils.HttpExecutionRequest.builder().method(HttpMethod.POST).url(url).parameters(parameters).build();
response = HttpUtils.execute(exec);
if (response != null) {
val status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
val result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
val results = MAPPER.readValue(JsonValue.readHjson(result).toString(), Map.class);
LOGGER.debug("Received results as [{}]", results);
val channelStatus = results.get("status").toString();
if ("expired".equalsIgnoreCase(channelStatus)) {
throw new AccountExpiredException("Authentication request has expired");
}
if ("declined".equalsIgnoreCase(channelStatus)) {
throw new FailedLoginException("Acceptto authentication has been declined");
}
if ("approved".equalsIgnoreCase(channelStatus)) {
val deviceId = results.get("device_id").toString();
val attr = CollectionUtils.<String, List<Object>>wrap("accepttoChannel", CollectionUtils.wrapList(tokenCredential.getId()), "accepttoDeviceId", CollectionUtils.wrapList(deviceId), "accepttoStatus", CollectionUtils.wrapList(channelStatus));
val principal = this.principalFactory.createPrincipal(email, attr);
return createHandlerResult(tokenCredential, principal);
}
}
if (status == HttpStatus.SC_FORBIDDEN) {
throw new AccountNotFoundException("Invalid uid and secret combination; application not found");
}
if (status == HttpStatus.SC_UNAUTHORIZED) {
throw new AccountLockedException("Email address provided is not a valid registered account");
}
}
} finally {
HttpUtils.close(response);
}
} catch (final Exception e) {
LoggingUtils.error(LOGGER, e);
}
throw new FailedLoginException("Acceptto authentication has failed");
}
use of javax.security.auth.login.AccountLockedException in project cas by apereo.
the class JsonResourceAuthenticationHandler method authenticateUsernamePasswordInternal.
@Override
protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential, final String originalPassword) throws GeneralSecurityException, PreventedException {
val map = readAccountsFromResource();
val username = credential.getUsername();
val password = credential.getPassword();
if (!map.containsKey(username)) {
throw new AccountNotFoundException();
}
val account = map.get(username);
if (matches(password, account.getPassword())) {
switch(account.getStatus()) {
case DISABLED:
throw new AccountDisabledException();
case EXPIRED:
throw new AccountExpiredException();
case LOCKED:
throw new AccountLockedException();
case MUST_CHANGE_PASSWORD:
throw new AccountPasswordMustChangeException();
case OK:
default:
LOGGER.debug("Account status is OK");
}
val clientInfo = ClientInfoHolder.getClientInfo();
if (clientInfo != null && StringUtils.isNotBlank(account.getLocation()) && !RegexUtils.find(account.getLocation(), clientInfo.getClientIpAddress())) {
throw new InvalidLoginLocationException("Unable to login from this location");
}
if (StringUtils.isNotBlank(account.getAvailability())) {
val range = Splitter.on("~").splitToList(account.getAvailability());
val startDate = DateTimeUtils.convertToZonedDateTime(range.get(0));
val endDate = DateTimeUtils.convertToZonedDateTime(range.get(1));
val now = ZonedDateTime.now(Clock.systemUTC());
if (now.isBefore(startDate) || now.isAfter(endDate)) {
throw new InvalidLoginTimeException("Unable to login at this time");
}
}
val warnings = new ArrayList<MessageDescriptor>();
if (account.getExpirationDate() != null) {
val now = LocalDate.now(ZoneOffset.UTC);
if (now.isEqual(account.getExpirationDate()) || now.isAfter(account.getExpirationDate())) {
throw new AccountExpiredException();
}
if (getPasswordPolicyConfiguration() != null) {
val warningPeriod = account.getExpirationDate().minusDays(getPasswordPolicyConfiguration().getPasswordWarningNumberOfDays());
if (now.isAfter(warningPeriod) || now.isEqual(warningPeriod)) {
val daysRemaining = ChronoUnit.DAYS.between(now, account.getExpirationDate());
warnings.add(new DefaultMessageDescriptor("password.expiration.loginsRemaining", "You have {0} logins remaining before you MUST change your password.", new Serializable[] { daysRemaining }));
}
}
}
account.getWarnings().forEach(warning -> warnings.add(new DefaultMessageDescriptor(warning, warning, new Serializable[] { username })));
val principal = this.principalFactory.createPrincipal(username, account.getAttributes());
return createHandlerResult(credential, principal, warnings);
}
throw new FailedLoginException();
}
Aggregations