Search in sources :

Example 6 with AccountPasswordMustChangeException

use of org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException 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();
}
Also used : lombok.val(lombok.val) AccountLockedException(javax.security.auth.login.AccountLockedException) Serializable(java.io.Serializable) FailedLoginException(javax.security.auth.login.FailedLoginException) AccountExpiredException(javax.security.auth.login.AccountExpiredException) InvalidLoginLocationException(org.apereo.cas.authentication.exceptions.InvalidLoginLocationException) DefaultMessageDescriptor(org.apereo.cas.DefaultMessageDescriptor) InvalidLoginTimeException(org.apereo.cas.authentication.exceptions.InvalidLoginTimeException) ArrayList(java.util.ArrayList) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException)

Example 7 with AccountPasswordMustChangeException

use of org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException in project cas by apereo.

the class AmazonCognitoAuthenticationAuthenticationHandler method authenticateUsernamePasswordInternal.

@Override
protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential, final String originalPassword) throws GeneralSecurityException {
    try {
        val authParams = new HashMap<String, String>();
        authParams.put("USERNAME", credential.getUsername());
        authParams.put("PASSWORD", credential.getPassword());
        val authRequest = AdminInitiateAuthRequest.builder();
        val request = authRequest.authFlow(AuthFlowType.ADMIN_NO_SRP_AUTH).clientId(properties.getClientId()).userPoolId(properties.getUserPoolId()).authParameters(authParams).build();
        val result = cognitoIdentityProvider.adminInitiateAuth(request);
        if ("NEW_PASSWORD_REQUIRED".equalsIgnoreCase(result.challengeNameAsString())) {
            throw new CredentialExpiredException();
        }
        val authenticationResult = result.authenticationResult();
        val claims = jwtProcessor.process(authenticationResult.idToken(), new SimpleSecurityContext());
        if (StringUtils.isBlank(claims.getSubject())) {
            throw new FailedLoginException("Unable to accept the id token with an invalid [sub] claim");
        }
        val userResult = cognitoIdentityProvider.adminGetUser(AdminGetUserRequest.builder().userPoolId(properties.getUserPoolId()).username(credential.getUsername()).build());
        val attributes = new LinkedHashMap<String, List<Object>>();
        attributes.put("userStatus", CollectionUtils.wrap(userResult.userStatusAsString()));
        attributes.put("userCreatedDate", CollectionUtils.wrap(userResult.userCreateDate().toEpochMilli()));
        attributes.put("userModifiedDate", CollectionUtils.wrap(userResult.userLastModifiedDate().toEpochMilli()));
        val userAttributes = userResult.userAttributes();
        userAttributes.forEach(attr -> {
            if (!properties.getMappedAttributes().isEmpty() && properties.getMappedAttributes().containsKey(attr.name())) {
                val newName = properties.getMappedAttributes().get(attr.name());
                attributes.put(newName, CollectionUtils.wrap(attr.value()));
            } else {
                attributes.put(attr.name(), CollectionUtils.wrap(attr.value()));
            }
        });
        val principal = principalFactory.createPrincipal(userResult.username(), attributes);
        return createHandlerResult(credential, principal, new ArrayList<>(0));
    } catch (final NotAuthorizedException e) {
        val message = e.getMessage();
        if (message.contains("expired")) {
            throw new AccountExpiredException(message);
        }
        if (message.contains("disabled")) {
            throw new AccountDisabledException(message);
        }
        throw new FailedLoginException(e.getMessage());
    } catch (final UserNotFoundException e) {
        throw new AccountNotFoundException(e.getMessage());
    } catch (final CredentialExpiredException e) {
        throw new AccountPasswordMustChangeException(e.getMessage());
    } catch (final InvalidPasswordException e) {
        throw new AccountPasswordMustChangeException(e.getMessage());
    } catch (final Exception e) {
        throw new FailedLoginException(e.getMessage());
    }
}
Also used : lombok.val(lombok.val) UserNotFoundException(software.amazon.awssdk.services.cognitoidentityprovider.model.UserNotFoundException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) NotAuthorizedException(software.amazon.awssdk.services.cognitoidentityprovider.model.NotAuthorizedException) UserNotFoundException(software.amazon.awssdk.services.cognitoidentityprovider.model.UserNotFoundException) AccountExpiredException(javax.security.auth.login.AccountExpiredException) CredentialExpiredException(javax.security.auth.login.CredentialExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) FailedLoginException(javax.security.auth.login.FailedLoginException) InvalidPasswordException(software.amazon.awssdk.services.cognitoidentityprovider.model.InvalidPasswordException) NotAuthorizedException(software.amazon.awssdk.services.cognitoidentityprovider.model.NotAuthorizedException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException) LinkedHashMap(java.util.LinkedHashMap) FailedLoginException(javax.security.auth.login.FailedLoginException) AccountExpiredException(javax.security.auth.login.AccountExpiredException) SimpleSecurityContext(com.nimbusds.jose.proc.SimpleSecurityContext) InvalidPasswordException(software.amazon.awssdk.services.cognitoidentityprovider.model.InvalidPasswordException) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException) CredentialExpiredException(javax.security.auth.login.CredentialExpiredException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException)

Example 8 with AccountPasswordMustChangeException

use of org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException in project cas by apereo.

the class QueryAndEncodeDatabaseAuthenticationHandler method authenticateUsernamePasswordInternal.

@Override
protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential transformedCredential, final String originalPassword) throws GeneralSecurityException, PreventedException {
    if (StringUtils.isBlank(properties.getSql()) || StringUtils.isBlank(properties.getAlgorithmName()) || getJdbcTemplate() == null) {
        throw new GeneralSecurityException("Authentication handler is not configured correctly");
    }
    val username = transformedCredential.getUsername();
    try {
        val values = getJdbcTemplate().queryForMap(properties.getSql(), username);
        val digestedPassword = digestEncodedPassword(transformedCredential.getPassword(), values);
        if (!values.get(properties.getPasswordFieldName()).equals(digestedPassword)) {
            throw new FailedLoginException("Password does not match value on record.");
        }
        if (StringUtils.isNotBlank(properties.getExpiredFieldName()) && values.containsKey(properties.getExpiredFieldName())) {
            val dbExpired = values.get(properties.getExpiredFieldName()).toString();
            if (BooleanUtils.toBoolean(dbExpired) || "1".equals(dbExpired)) {
                throw new AccountPasswordMustChangeException("Password has expired");
            }
        }
        if (StringUtils.isNotBlank(properties.getDisabledFieldName()) && values.containsKey(properties.getDisabledFieldName())) {
            val dbDisabled = values.get(properties.getDisabledFieldName()).toString();
            if (BooleanUtils.toBoolean(dbDisabled) || "1".equals(dbDisabled)) {
                throw new AccountDisabledException("Account has been disabled");
            }
        }
        return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(username), new ArrayList<>(0));
    } catch (final IncorrectResultSizeDataAccessException e) {
        if (e.getActualSize() == 0) {
            throw new AccountNotFoundException(username + " not found with SQL query");
        }
        throw new FailedLoginException("Multiple records found for " + username);
    } catch (final DataAccessException e) {
        throw new PreventedException(e);
    }
}
Also used : lombok.val(lombok.val) FailedLoginException(javax.security.auth.login.FailedLoginException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) GeneralSecurityException(java.security.GeneralSecurityException) PreventedException(org.apereo.cas.authentication.PreventedException) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException) DataAccessException(org.springframework.dao.DataAccessException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException)

Example 9 with AccountPasswordMustChangeException

use of org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException in project cas by apereo.

the class SyncopeAuthenticationHandler method authenticateUsernamePasswordInternal.

@Override
@SneakyThrows
protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential, final String originalPassword) {
    val result = authenticateSyncopeUser(credential);
    if (result.isPresent()) {
        val user = result.get();
        LOGGER.debug("Received user object as [{}]", user);
        if (user.has("suspended") && user.get("suspended").asBoolean()) {
            throw new AccountDisabledException("Could not authenticate forbidden account for " + credential.getUsername());
        }
        if (user.has("mustChangePassword") && user.get("mustChangePassword").asBoolean()) {
            throw new AccountPasswordMustChangeException("Account password must change for " + credential.getUsername());
        }
        val principal = this.principalFactory.createPrincipal(user.get("username").asText(), SyncopeUserTOConverterUtils.convert(user));
        return createHandlerResult(credential, principal, new ArrayList<>(0));
    }
    throw new FailedLoginException("Could not authenticate account for " + credential.getUsername());
}
Also used : lombok.val(lombok.val) FailedLoginException(javax.security.auth.login.FailedLoginException) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException) SneakyThrows(lombok.SneakyThrows)

Aggregations

FailedLoginException (javax.security.auth.login.FailedLoginException)9 AccountDisabledException (org.apereo.cas.authentication.exceptions.AccountDisabledException)9 AccountPasswordMustChangeException (org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException)9 lombok.val (lombok.val)8 AccountNotFoundException (javax.security.auth.login.AccountNotFoundException)7 AccountExpiredException (javax.security.auth.login.AccountExpiredException)5 AccountLockedException (javax.security.auth.login.AccountLockedException)4 GeneralSecurityException (java.security.GeneralSecurityException)3 ArrayList (java.util.ArrayList)2 LinkedHashMap (java.util.LinkedHashMap)2 HttpResponse (org.apache.http.HttpResponse)2 PreventedException (org.apereo.cas.authentication.PreventedException)2 DataAccessException (org.springframework.dao.DataAccessException)2 IncorrectResultSizeDataAccessException (org.springframework.dao.IncorrectResultSizeDataAccessException)2 SimpleSecurityContext (com.nimbusds.jose.proc.SimpleSecurityContext)1 Serializable (java.io.Serializable)1 HashMap (java.util.HashMap)1 List (java.util.List)1 CredentialExpiredException (javax.security.auth.login.CredentialExpiredException)1 SneakyThrows (lombok.SneakyThrows)1