Search in sources :

Example 6 with AccountExpiredException

use of javax.security.auth.login.AccountExpiredException in project cas by apereo.

the class GoogleAuthenticatorAuthenticationHandler method doAuthentication.

@Override
protected AuthenticationHandlerExecutionResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    final GoogleAuthenticatorTokenCredential tokenCredential = (GoogleAuthenticatorTokenCredential) credential;
    if (!StringUtils.isNumeric(tokenCredential.getToken())) {
        throw new PreventedException("Invalid non-numeric OTP format specified.", new IllegalArgumentException("Invalid token " + tokenCredential.getToken()));
    }
    final int otp = Integer.parseInt(tokenCredential.getToken());
    LOGGER.debug("Received OTP [{}]", otp);
    @NonNull final Authentication authentication = WebUtils.getInProgressAuthentication();
    final String uid = authentication.getPrincipal().getId();
    LOGGER.debug("Received principal id [{}]", uid);
    final OneTimeTokenAccount acct = this.credentialRepository.get(uid);
    if (acct == null || StringUtils.isBlank(acct.getSecretKey())) {
        throw new AccountNotFoundException(uid + " cannot be found in the registry");
    }
    if (this.tokenRepository.exists(uid, otp)) {
        throw new AccountExpiredException(uid + " cannot reuse OTP " + otp + " as it may be expired/invalid");
    }
    boolean isCodeValid = this.googleAuthenticatorInstance.authorize(acct.getSecretKey(), otp);
    if (!isCodeValid && acct.getScratchCodes().contains(otp)) {
        LOGGER.warn("Using scratch code [{}] to authenticate user [{}]. Scratch code will be removed", otp, uid);
        acct.getScratchCodes().removeIf(token -> token == otp);
        this.credentialRepository.update(acct);
        isCodeValid = true;
    }
    if (isCodeValid) {
        this.tokenRepository.store(new GoogleAuthenticatorToken(otp, uid));
        return createHandlerResult(tokenCredential, this.principalFactory.createPrincipal(uid));
    }
    throw new FailedLoginException("Failed to authenticate code " + otp);
}
Also used : OneTimeTokenAccount(org.apereo.cas.otp.repository.credentials.OneTimeTokenAccount) FailedLoginException(javax.security.auth.login.FailedLoginException) Authentication(org.apereo.cas.authentication.Authentication) AccountExpiredException(javax.security.auth.login.AccountExpiredException) NonNull(lombok.NonNull) GoogleAuthenticatorToken(org.apereo.cas.adaptors.gauth.token.GoogleAuthenticatorToken) PreventedException(org.apereo.cas.authentication.PreventedException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException)

Example 7 with AccountExpiredException

use of javax.security.auth.login.AccountExpiredException in project tomcat70 by apache.

the class JAASRealm method authenticate.

// -------------------------------------------------------- Package Methods
// ------------------------------------------------------ Protected Methods
/**
 * Perform the actual JAAS authentication
 */
protected Principal authenticate(String username, CallbackHandler callbackHandler) {
    // Establish a LoginContext to use for authentication
    try {
        LoginContext loginContext = null;
        if (appName == null)
            appName = "Tomcat";
        if (log.isDebugEnabled())
            log.debug(sm.getString("jaasRealm.beginLogin", username, appName));
        // What if the LoginModule is in the container class loader ?
        ClassLoader ocl = null;
        if (!isUseContextClassLoader()) {
            ocl = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        }
        try {
            Configuration config = getConfig();
            loginContext = new LoginContext(appName, null, callbackHandler, config);
        } catch (Throwable e) {
            ExceptionUtils.handleThrowable(e);
            log.error(sm.getString("jaasRealm.unexpectedError"), e);
            return (null);
        } finally {
            if (!isUseContextClassLoader()) {
                Thread.currentThread().setContextClassLoader(ocl);
            }
        }
        if (log.isDebugEnabled())
            log.debug("Login context created " + username);
        // Negotiate a login via this LoginContext
        Subject subject = null;
        try {
            loginContext.login();
            subject = loginContext.getSubject();
            if (subject == null) {
                if (log.isDebugEnabled())
                    log.debug(sm.getString("jaasRealm.failedLogin", username));
                return (null);
            }
        } catch (AccountExpiredException e) {
            if (log.isDebugEnabled())
                log.debug(sm.getString("jaasRealm.accountExpired", username));
            return (null);
        } catch (CredentialExpiredException e) {
            if (log.isDebugEnabled())
                log.debug(sm.getString("jaasRealm.credentialExpired", username));
            return (null);
        } catch (FailedLoginException e) {
            if (log.isDebugEnabled())
                log.debug(sm.getString("jaasRealm.failedLogin", username));
            return (null);
        } catch (LoginException e) {
            log.warn(sm.getString("jaasRealm.loginException", username), e);
            return (null);
        } catch (Throwable e) {
            ExceptionUtils.handleThrowable(e);
            log.error(sm.getString("jaasRealm.unexpectedError"), e);
            return (null);
        }
        if (log.isDebugEnabled())
            log.debug(sm.getString("jaasRealm.loginContextCreated", username));
        // Return the appropriate Principal for this authenticated Subject
        Principal principal = createPrincipal(username, subject, loginContext);
        if (principal == null) {
            log.debug(sm.getString("jaasRealm.authenticateFailure", username));
            return (null);
        }
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("jaasRealm.authenticateSuccess", username));
        }
        return (principal);
    } catch (Throwable t) {
        log.error("error ", t);
        return null;
    }
}
Also used : LoginContext(javax.security.auth.login.LoginContext) FailedLoginException(javax.security.auth.login.FailedLoginException) Configuration(javax.security.auth.login.Configuration) AccountExpiredException(javax.security.auth.login.AccountExpiredException) LoginException(javax.security.auth.login.LoginException) FailedLoginException(javax.security.auth.login.FailedLoginException) CredentialExpiredException(javax.security.auth.login.CredentialExpiredException) Subject(javax.security.auth.Subject) Principal(java.security.Principal)

Example 8 with AccountExpiredException

use of javax.security.auth.login.AccountExpiredException 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");
}
Also used : lombok.val(lombok.val) AccountLockedException(javax.security.auth.login.AccountLockedException) FailedLoginException(javax.security.auth.login.FailedLoginException) AccountExpiredException(javax.security.auth.login.AccountExpiredException) HttpResponse(org.apache.http.HttpResponse) List(java.util.List) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) AccountExpiredException(javax.security.auth.login.AccountExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) FailedLoginException(javax.security.auth.login.FailedLoginException) AccountLockedException(javax.security.auth.login.AccountLockedException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException)

Example 9 with AccountExpiredException

use of javax.security.auth.login.AccountExpiredException 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 10 with AccountExpiredException

use of javax.security.auth.login.AccountExpiredException 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)

Aggregations

AccountExpiredException (javax.security.auth.login.AccountExpiredException)11 FailedLoginException (javax.security.auth.login.FailedLoginException)9 AccountNotFoundException (javax.security.auth.login.AccountNotFoundException)8 lombok.val (lombok.val)8 AccountLockedException (javax.security.auth.login.AccountLockedException)5 AccountDisabledException (org.apereo.cas.authentication.exceptions.AccountDisabledException)5 AccountPasswordMustChangeException (org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException)5 CredentialExpiredException (javax.security.auth.login.CredentialExpiredException)4 GeneralSecurityException (java.security.GeneralSecurityException)3 Principal (java.security.Principal)2 LinkedHashMap (java.util.LinkedHashMap)2 Subject (javax.security.auth.Subject)2 Configuration (javax.security.auth.login.Configuration)2 LoginContext (javax.security.auth.login.LoginContext)2 LoginException (javax.security.auth.login.LoginException)2 HttpResponse (org.apache.http.HttpResponse)2 Authentication (org.apereo.cas.authentication.Authentication)2 PreventedException (org.apereo.cas.authentication.PreventedException)2 SimpleSecurityContext (com.nimbusds.jose.proc.SimpleSecurityContext)1 IGoogleAuthenticator (com.warrenstrange.googleauth.IGoogleAuthenticator)1