Search in sources :

Example 1 with FailedLoginException

use of javax.security.auth.login.FailedLoginException in project tomcat by apache.

the class JAASRealm method authenticate.

// -------------------------------------------------------- Package Methods
// ------------------------------------------------------ Protected Methods
/**
     * Perform the actual JAAS authentication.
     * @param username The user name
     * @param callbackHandler The callback handler
     * @return the associated principal, or <code>null</code> if there is none.
     */
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 2 with FailedLoginException

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

the class HttpBasedServiceCredentialsAuthenticationHandler method authenticate.

@Override
public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException {
    final HttpBasedServiceCredential httpCredential = (HttpBasedServiceCredential) credential;
    if (!httpCredential.getService().getProxyPolicy().isAllowedProxyCallbackUrl(httpCredential.getCallbackUrl())) {
        LOGGER.warn("Proxy policy for service [{}] cannot authorize the requested callback url [{}].", httpCredential.getService().getServiceId(), httpCredential.getCallbackUrl());
        throw new FailedLoginException(httpCredential.getCallbackUrl() + " cannot be authorized");
    }
    LOGGER.debug("Attempting to authenticate [{}]", httpCredential);
    final URL callbackUrl = httpCredential.getCallbackUrl();
    if (!this.httpClient.isValidEndPoint(callbackUrl)) {
        throw new FailedLoginException(callbackUrl.toExternalForm() + " sent an unacceptable response status code");
    }
    return new DefaultHandlerResult(this, httpCredential, this.principalFactory.createPrincipal(httpCredential.getId()));
}
Also used : HttpBasedServiceCredential(org.apereo.cas.authentication.HttpBasedServiceCredential) FailedLoginException(javax.security.auth.login.FailedLoginException) DefaultHandlerResult(org.apereo.cas.authentication.DefaultHandlerResult) URL(java.net.URL)

Example 3 with FailedLoginException

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

the class AuthyAuthenticationHandler method doAuthentication.

@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    final AuthyTokenCredential tokenCredential = (AuthyTokenCredential) credential;
    final RequestContext context = RequestContextHolder.getRequestContext();
    final Principal principal = WebUtils.getAuthentication(context).getPrincipal();
    final User user = instance.getOrCreateUser(principal);
    if (!user.isOk()) {
        throw new FailedLoginException(AuthyClientInstance.getErrorMessage(user.getError()));
    }
    final Map<String, String> options = new HashMap<>(1);
    options.put("force", this.forceVerification.toString());
    final Token verification = this.instance.getAuthyTokens().verify(user.getId(), tokenCredential.getToken(), options);
    if (!verification.isOk()) {
        throw new FailedLoginException(AuthyClientInstance.getErrorMessage(verification.getError()));
    }
    return createHandlerResult(tokenCredential, principal, new ArrayList<>());
}
Also used : User(com.authy.api.User) FailedLoginException(javax.security.auth.login.FailedLoginException) HashMap(java.util.HashMap) Token(com.authy.api.Token) RequestContext(org.springframework.webflow.execution.RequestContext) Principal(org.apereo.cas.authentication.principal.Principal)

Example 4 with FailedLoginException

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

the class DuoAuthenticationHandler method authenticateDuoCredential.

private HandlerResult authenticateDuoCredential(final Credential credential) throws FailedLoginException {
    try {
        final DuoCredential duoCredential = (DuoCredential) credential;
        if (!duoCredential.isValid()) {
            throw new GeneralSecurityException("Duo credential validation failed. Ensure a username " + " and the signed Duo response is configured and passed. Credential received: " + duoCredential);
        }
        final DuoAuthenticationService duoAuthenticationService = getDuoAuthenticationService();
        final String duoVerifyResponse = duoAuthenticationService.authenticate(duoCredential).getValue();
        LOGGER.debug("Response from Duo verify: [{}]", duoVerifyResponse);
        final String primaryCredentialsUsername = duoCredential.getUsername();
        final boolean isGoodAuthentication = duoVerifyResponse.equals(primaryCredentialsUsername);
        if (isGoodAuthentication) {
            LOGGER.info("Successful Duo authentication for [{}]", primaryCredentialsUsername);
            final Principal principal = this.principalFactory.createPrincipal(duoVerifyResponse);
            return createHandlerResult(credential, principal, new ArrayList<>());
        }
        throw new FailedLoginException("Duo authentication username " + primaryCredentialsUsername + " does not match Duo response: " + duoVerifyResponse);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new FailedLoginException(e.getMessage());
    }
}
Also used : FailedLoginException(javax.security.auth.login.FailedLoginException) GeneralSecurityException(java.security.GeneralSecurityException) Principal(org.apereo.cas.authentication.principal.Principal) GeneralSecurityException(java.security.GeneralSecurityException) FailedLoginException(javax.security.auth.login.FailedLoginException) PreventedException(org.apereo.cas.authentication.PreventedException)

Example 5 with FailedLoginException

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

the class QueryDatabaseAuthenticationHandler method authenticateUsernamePasswordInternal.

@Override
protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential, final String originalPassword) throws GeneralSecurityException, PreventedException {
    if (StringUtils.isBlank(this.sql) || getJdbcTemplate() == null) {
        throw new GeneralSecurityException("Authentication handler is not configured correctly. " + "No SQL statement or JDBC template is found.");
    }
    final Map<String, Object> attributes = new LinkedHashMap<>(this.principalAttributeMap.size());
    final String username = credential.getUsername();
    final String password = credential.getPassword();
    try {
        final Map<String, Object> dbFields = getJdbcTemplate().queryForMap(this.sql, username);
        final String dbPassword = (String) dbFields.get(this.fieldPassword);
        if (StringUtils.isNotBlank(originalPassword) && !matches(originalPassword, dbPassword) || StringUtils.isBlank(originalPassword) && !StringUtils.equals(password, dbPassword)) {
            throw new FailedLoginException("Password does not match value on record.");
        }
        if (StringUtils.isNotBlank(this.fieldDisabled)) {
            final Object dbDisabled = dbFields.get(this.fieldDisabled);
            if (dbDisabled != null && (Boolean.TRUE.equals(BooleanUtils.toBoolean(dbDisabled.toString())) || dbDisabled.equals(Integer.valueOf(1)))) {
                throw new AccountDisabledException("Account has been disabled");
            }
        }
        if (StringUtils.isNotBlank(this.fieldExpired)) {
            final Object dbExpired = dbFields.get(this.fieldExpired);
            if (dbExpired != null && (Boolean.TRUE.equals(BooleanUtils.toBoolean(dbExpired.toString())) || dbExpired.equals(Integer.valueOf(1)))) {
                throw new AccountPasswordMustChangeException("Password has expired");
            }
        }
        this.principalAttributeMap.entrySet().forEach(a -> {
            final Object attribute = dbFields.get(a.getKey());
            if (attribute != null) {
                LOGGER.debug("Found attribute [{}] from the query results", a);
                if (attribute != null) {
                    LOGGER.debug("Found attribute [{}] from the query results", a);
                    final String principalAttrName = a.getValue();
                    attributes.put(principalAttrName, attribute.toString());
                } else {
                    LOGGER.warn("Requested attribute [{}] could not be found in the query results", a.getKey());
                }
            }
        });
    } 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("SQL exception while executing query for " + username, e);
    }
    return createHandlerResult(credential, this.principalFactory.createPrincipal(username, attributes), null);
}
Also used : 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) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

FailedLoginException (javax.security.auth.login.FailedLoginException)67 LoginException (javax.security.auth.login.LoginException)20 Callback (javax.security.auth.callback.Callback)15 NameCallback (javax.security.auth.callback.NameCallback)15 PasswordCallback (javax.security.auth.callback.PasswordCallback)15 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)15 IOException (java.io.IOException)14 PreventedException (org.apereo.cas.authentication.PreventedException)14 GeneralSecurityException (java.security.GeneralSecurityException)13 LoginContext (javax.security.auth.login.LoginContext)10 AccountNotFoundException (javax.security.auth.login.AccountNotFoundException)9 DefaultHandlerResult (org.apereo.cas.authentication.DefaultHandlerResult)9 Subject (javax.security.auth.Subject)8 RolePrincipal (org.apache.karaf.jaas.boot.principal.RolePrincipal)7 Principal (org.apereo.cas.authentication.principal.Principal)7 BasicCredentialMetaData (org.apereo.cas.authentication.BasicCredentialMetaData)6 File (java.io.File)5 Principal (java.security.Principal)5 AccountDisabledException (org.apereo.cas.authentication.exceptions.AccountDisabledException)5 RequestContext (org.springframework.webflow.execution.RequestContext)5