Search in sources :

Example 6 with InvalidPasswordException

use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.

the class Membership method loginUser.

private ModuleState loginUser(Callback[] callbacks) throws AuthLoginException {
    String password = null;
    Callback[] idCallbacks = new Callback[2];
    try {
        if (callbacks != null && callbacks.length == 0) {
            userName = (String) sharedState.get(getUserKey());
            password = (String) sharedState.get(getPwdKey());
            if (userName == null || password == null) {
                return ModuleState.LOGIN_START;
            }
            getCredentialsFromSharedState = true;
            NameCallback nameCallback = new NameCallback("dummy");
            nameCallback.setName(userName);
            idCallbacks[0] = nameCallback;
            PasswordCallback passwordCallback = new PasswordCallback("dummy", false);
            passwordCallback.setPassword(password.toCharArray());
            idCallbacks[1] = passwordCallback;
        } else {
            idCallbacks = callbacks;
            //callbacks is not null
            userName = ((NameCallback) callbacks[0]).getName();
            password = String.valueOf(((PasswordCallback) callbacks[1]).getPassword());
        }
        if (password == null || password.length() == 0) {
            if (debug.messageEnabled()) {
                debug.message("Membership.loginUser: Password is null/empty");
            }
            throw new InvalidPasswordException("amAuth", "invalidPasswd", null);
        }
        //store username password both in success and failure case
        storeUsernamePasswd(userName, password);
        initAuthConfig();
        AMIdentityRepository idrepo = getAMIdentityRepository(getRequestOrg());
        boolean success = idrepo.authenticate(idCallbacks);
        if (success) {
            validatedUserID = userName;
            return ModuleState.COMPLETE;
        } else {
            throw new AuthLoginException(amAuthMembership, "authFailed", null);
        }
    } catch (IdRepoException ex) {
        if (getCredentialsFromSharedState && !isUseFirstPassEnabled()) {
            getCredentialsFromSharedState = false;
            return ModuleState.LOGIN_START;
        }
        if (debug.warningEnabled()) {
            debug.warning("idRepo Exception");
        }
        setFailureID(userName);
        throw new AuthLoginException(amAuthMembership, "authFailed", null, ex);
    }
}
Also used : PasswordCallback(javax.security.auth.callback.PasswordCallback) ChoiceCallback(javax.security.auth.callback.ChoiceCallback) NameCallback(javax.security.auth.callback.NameCallback) ConfirmationCallback(javax.security.auth.callback.ConfirmationCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) IdRepoException(com.sun.identity.idm.IdRepoException) PasswordCallback(javax.security.auth.callback.PasswordCallback) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException)

Example 7 with InvalidPasswordException

use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.

the class AMLoginContext method runLogin.

/**
     * Starts the login process ,calls JAAS Login Context
     */
public void runLogin() {
    Thread thread = Thread.currentThread();
    String logFailedMessage = bundle.getString("loginFailed");
    String logFailedError = null;
    AuthenticationFailureReason failureReason = null;
    AMAccountLockout amAccountLockout;
    boolean loginSuccess = false;
    try {
        if (isPureJAAS()) {
            loginContext.login();
            subject = loginContext.getSubject();
        } else {
            jaasLoginContext.login();
            subject = jaasLoginContext.getSubject();
        }
        loginState.setSubject(subject);
        if (!loginState.isAuthValidForInternalUser()) {
            if (debug.warningEnabled()) {
                debug.warning("AMLoginContext.runLogin():auth failed, " + "using invalid realm name for internal user");
            }
            logFailedMessage = AuthUtils.getErrorVal(AMAuthErrorCode.AUTH_MODULE_DENIED, AuthUtils.ERROR_MESSAGE);
            logFailedError = "MODULEDENIED";
            failureReason = MODULE_DENIED;
            throw new AuthException(AMAuthErrorCode.AUTH_MODULE_DENIED, null);
        }
        debug.message("user authentication successful");
        // retrieve authenticated user's profile or create
        // a user profile if dynamic profile creation is
        // is true
        debug.message("searchUserProfile for Subject :");
        boolean profileState = loginState.searchUserProfile(subject, indexType, indexName);
        loginState.saveSubjectState();
        loginSuccess = true;
        if (!profileState) {
            debug.error("Profile not found ");
            logFailedMessage = bundle.getString("noUserProfile");
            logFailedError = "NOUSERPROFILE";
            failureReason = NO_USER_PROFILE;
            loginState.setErrorCode(AMAuthErrorCode.AUTH_PROFILE_ERROR);
            isFailed = true;
        } else {
            //update loginstate with authlevel , moduleName , role etc.
            amAccountLockout = new AMAccountLockout(loginState);
            if (amAccountLockout.isLockedOut()) {
                debug.message("User locked out!!");
                logFailedMessage = bundle.getString("lockOut");
                logFailedError = "LOCKEDOUT";
                failureReason = LOCKED_OUT;
                loginState.setErrorCode(AMAuthErrorCode.AUTH_USER_LOCKED);
                isFailed = true;
            } else {
                boolean accountExpired = false;
                if (!loginState.ignoreProfile()) {
                    accountExpired = amAccountLockout.isAccountExpired();
                }
                if (accountExpired) {
                    debug.message("Account expired!!");
                    logFailedMessage = bundle.getString("accountExpired");
                    logFailedError = "ACCOUNTEXPIRED";
                    failureReason = ACCOUNT_EXPIRED;
                    loginState.setErrorCode(AMAuthErrorCode.AUTH_ACCOUNT_EXPIRED);
                    isFailed = true;
                } else {
                    // came here successful auth.
                    if (debug.messageEnabled()) {
                        debug.message("authContext is : " + authContext);
                        debug.message("loginSTate is : " + loginState);
                    }
                    updateLoginState(indexType, indexName, configName, orgDN);
                    //activate session
                    Object lcInSession;
                    if (isPureJAAS()) {
                        lcInSession = loginContext;
                    } else {
                        lcInSession = jaasLoginContext;
                    }
                    boolean sessionActivated = loginState.activateSession(subject, authContext, lcInSession);
                    if (sessionActivated) {
                        loginState.logSuccess();
                        auditor.auditLoginSuccess(loginState);
                        if (amAccountLockout.isLockoutEnabled()) {
                            amAccountLockout.resetPasswdLockout(loginState.getUserDN(), true);
                        }
                        loginStatus.setStatus(LoginStatus.AUTH_SUCCESS);
                        loginState.updateSessionForFailover();
                        debug.message("login success");
                    } else {
                        logFailedMessage = AuthUtils.getErrorVal(AMAuthErrorCode.AUTH_MAX_SESSION_REACHED, AuthUtils.ERROR_MESSAGE);
                        logFailedError = "MAXSESSIONREACHED";
                        failureReason = MAX_SESSION_REACHED;
                        throw new AuthException(AMAuthErrorCode.AUTH_MAX_SESSION_REACHED, null);
                    }
                }
            }
        }
    } catch (InvalidPasswordException ipe) {
        debug.message("Invalid Password : ");
        if (debug.messageEnabled()) {
            debug.message("Exception ", ipe);
        }
        String failedUserId = ipe.getTokenId();
        if (debug.messageEnabled()) {
            debug.message("Invalid Password Exception " + failedUserId);
        }
        if (failedUserId != null) {
            amAccountLockout = new AMAccountLockout(loginState);
            accountLocked = amAccountLockout.isLockedOut(failedUserId);
            if ((!accountLocked) && (amAccountLockout.isLockoutEnabled())) {
                amAccountLockout.invalidPasswd(failedUserId);
                checkWarningCount(amAccountLockout);
                accountLocked = amAccountLockout.isAccountLocked(failedUserId);
            }
        }
        logFailedMessage = bundle.getString("invalidPasswd");
        logFailedError = "INVALIDPASSWORD";
        failureReason = INVALID_PASSWORD;
        if (accountLocked) {
            if (failedUserId != null) {
                loginState.logFailed(failedUserId, "LOCKEDOUT");
            } else {
                loginState.logFailed("LOCKEDOUT");
            }
            auditor.auditLoginFailure(loginState, LOCKED_OUT);
        }
        loginState.setErrorCode(AMAuthErrorCode.AUTH_LOGIN_FAILED);
        isFailed = true;
        authContext.setLoginException(ipe);
    } catch (AuthErrorCodeException e) {
        if (debug.messageEnabled()) {
            debug.message(e.getMessage());
        }
        isFailed = true;
        java.util.Locale locale = com.sun.identity.shared.locale.Locale.getLocale(loginState.getLocale());
        loginState.setModuleErrorMessage(e.getL10NMessage(locale));
        loginState.setErrorCode(e.getAuthErrorCode());
        authContext.setLoginException(e);
    } catch (MessageLoginException me) {
        if (debug.messageEnabled()) {
            debug.message("LOGINFAILED MessageAuthLoginException....");
            debug.message("Exception ", me);
        }
        java.util.Locale locale = com.sun.identity.shared.locale.Locale.getLocale(loginState.getLocale());
        loginState.setModuleErrorMessage(me.getL10NMessage(locale));
        loginState.setErrorMessage(me.getL10NMessage(locale));
        isFailed = true;
        authContext.setLoginException(me);
    } catch (AuthLoginException le) {
        loginState.setErrorCode(AMAuthErrorCode.AUTH_LOGIN_FAILED);
        if (AMAuthErrorCode.AUTH_MODULE_DENIED.equals(le.getMessage())) {
            if (debug.warningEnabled()) {
                debug.warning("AMLoginContext.runLogin():auth failed, using invalid auth module name for internal user");
            }
            logFailedMessage = AuthUtils.getErrorVal(AMAuthErrorCode.AUTH_MODULE_DENIED, AuthUtils.ERROR_MESSAGE);
            logFailedError = "MODULEDENIED";
            failureReason = MODULE_DENIED;
            loginState.setErrorCode(AMAuthErrorCode.AUTH_MODULE_DENIED);
        } else if (AMAuthErrorCode.AUTH_TIMEOUT.equals(le.getMessage())) {
            debug.message("LOGINFAILED Error Timed Out....");
        } else if (ISAuthConstants.EXCEED_RETRY_LIMIT.equals(le.getErrorCode())) {
            debug.message("LOGINFAILED ExceedRetryLimit");
        } else {
            debug.message("LOGINFAILED Error....");
        }
        if (debug.messageEnabled()) {
            debug.message("Exception : ", le);
        }
        isFailed = true;
        if (loginState.isTimedOut()) {
            logFailedMessage = bundle.getString("loginTimeout");
            logFailedError = "LOGINTIMEOUT";
            failureReason = LOGIN_TIMEOUT;
            loginState.setErrorCode(AMAuthErrorCode.AUTH_TIMEOUT);
        } else if (ISAuthConstants.EXCEED_RETRY_LIMIT.equals(le.getErrorCode())) {
            loginState.setErrorMessage(exceedRetryLimit);
            loginState.setErrorCode(AMAuthErrorCode.AUTH_USER_LOCKED_IN_DS);
        } else if (ISAuthConstants.SERVER_UNWILLING.equals(le.getErrorCode())) {
            loginState.setErrorCode(AMAuthErrorCode.AUTH_ERROR);
        }
        authContext.setLoginException(le);
    } catch (AuthException e) {
        if (debug.messageEnabled()) {
            debug.message("Exception : " + e.getMessage());
        }
        isFailed = true;
        loginState.setErrorCode(e.getErrorCode());
        loginState.logFailed(bundle.getString("loginFailed"));
        logFailedError = null;
        authContext.setLoginException(new AuthLoginException(BUNDLE_NAME, "loginFailed", null, e));
    } catch (Exception e) {
        debug.message("Error during login.. ");
        if (debug.messageEnabled()) {
            debug.message("Exception ", e);
        }
        isFailed = true;
        loginState.setErrorCode(AMAuthErrorCode.AUTH_ERROR);
        loginState.logFailed(bundle.getString("loginFailed"));
        logFailedError = null;
        authContext.setLoginException(new AuthLoginException(BUNDLE_NAME, "loginFailed", null, e));
    } catch (DSAMECallbackHandlerError error) {
        debug.message("Caught error returned from DSAMEHandler");
        return;
    }
    debug.message("Came to before if Failed loop");
    if (isFailed) {
        if (MonitoringUtil.isRunning()) {
            if (authImpl == null) {
                authImpl = Agent.getAuthSvcMBean();
            }
            if (authImpl != null) {
                authImpl.incSsoServerAuthenticationFailureCount();
            }
        }
        if (loginSuccess) {
            // this is the case where authentication to modules
            // succeeded but framework failed to validate the
            // user, in this case populate with all module user
            // successfully authenticated as.
            loginState.setFailureModuleList(getSuccessModuleString(orgDN));
        } else {
            loginState.setFailureModuleList(getFailureModuleList(orgDN));
        }
        loginState.logFailed(logFailedMessage, logFailedError);
        auditor.auditLoginFailure(loginState, failureReason);
        setErrorMsgAndTemplate();
        loginStatus.setStatus(LoginStatus.AUTH_FAILED);
        if (indexType == IndexType.USER) {
            if (debug.messageEnabled()) {
                debug.message("Set failureId in user based auth " + indexName);
            }
            loginState.setFailedUserId(indexName);
        }
    } else {
        if (debug.messageEnabled()) {
            debug.message("AMLoginContext.runLogin: calling incSsoServerAuthenticationSuccessCount");
        }
        if (MonitoringUtil.isRunning()) {
            if (authImpl == null) {
                authImpl = Agent.getAuthSvcMBean();
            }
        }
        if (authImpl != null && !loginState.isNoSession()) {
            authImpl.incSsoServerAuthenticationSuccessCount();
        }
    }
    if (debug.messageEnabled()) {
        debug.message("finished...login notify all threads\n" + "AMLoginContext:LoginStatus: " + loginStatus.getStatus());
    }
    if (isPureJAAS()) {
        authThread.removeFromHash(thread, "timeoutHash");
        // notify possible waiting thread
        loginState.setReceivedCallback(null, this);
    }
    isFailed = false;
    nullifyUsedVars();
}
Also used : DSAMECallbackHandlerError(com.sun.identity.authentication.service.DSAMECallbackHandler.DSAMECallbackHandlerError) MessageLoginException(com.sun.identity.authentication.spi.MessageLoginException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) LoginException(javax.security.auth.login.LoginException) MessageLoginException(com.sun.identity.authentication.spi.MessageLoginException) AuthErrorCodeException(com.sun.identity.authentication.spi.AuthErrorCodeException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) SSOException(com.iplanet.sso.SSOException) AMConfigurationException(com.sun.identity.authentication.config.AMConfigurationException) AuthenticationFailureReason(org.forgerock.openam.audit.AuditConstants.AuthenticationFailureReason) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) AuthErrorCodeException(com.sun.identity.authentication.spi.AuthErrorCodeException)

Example 8 with InvalidPasswordException

use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.

the class AuthenticatorOATH method checkOTP.

/**
     * Checks the input OTP.
     *
     * @param otp The OTP to verify.
     * @param id The user for whom to verify the OTP.
     * @param settings With which the OTP was configured.
     * @return true if the OTP is valid; false if the OTP is invalid, or out of
     *         sync with server.
     * @throws AuthLoginException on any error
     */
private boolean checkOTP(String otp, AMIdentity id, OathDeviceSettings settings) throws AuthLoginException {
    //check settings aren't null
    if (settings == null) {
        debug.error("OATH.checkOTP() : Invalid stored settings.");
        throw new AuthLoginException(amAuthOATH, "authFailed", null);
    }
    String secretKey = parseSecretKey(settings.getSharedSecret());
    if (minSecretKeyLength <= 0) {
        debug.error("OATH.checkOTP() : Min Secret Key Length is not a valid value");
        throw new AuthLoginException(amAuthOATH, "authFailed", null);
    }
    //check size of key
    if (secretKey == null || secretKey.isEmpty()) {
        debug.error("OATH.checkOTP() : Secret key is not a valid value");
        throw new AuthLoginException(amAuthOATH, "authFailed", null);
    }
    //make sure secretkey is not smaller than minSecretKeyLength
    if (secretKey.length() < minSecretKeyLength) {
        if (debug.errorEnabled()) {
            debug.error("OATH.checkOTP() : Secret key of length " + secretKey.length() + " is less than the minimum secret key length");
        }
        throw new AuthLoginException(amAuthOATH, "authFailed", null);
    }
    //convert secretkey hex string to hex.     
    byte[] secretKeyBytes = DatatypeConverter.parseHexBinary(secretKey);
    //check password length MUST be 6 or higher according to RFC
    if (passLen < 6) {
        debug.error("OATH.checkOTP() : Password length is smaller than 6");
        throw new AuthLoginException(amAuthOATH, "authFailed", null);
    }
    String otpGen;
    try {
        if (algorithm == HOTP) {
            /*
                 * HOTP check section
                 */
            int counter = settings.getCounter();
            //test the counter in the lookahead window
            for (int i = 0; i <= windowSize; i++) {
                otpGen = HOTPAlgorithm.generateOTP(secretKeyBytes, counter + i, passLen, checksum, truncationOffset);
                if (isEqual(otpGen, otp)) {
                    //OTP is correct set the counter value to counter+i (+1 for having been successful)
                    setCounterAttr(id, counter + i + 1, settings);
                    return true;
                }
            }
        } else if (algorithm == TOTP) {
            /*
                 * TOTP check section
                 */
            //get Last login time
            long lastLoginTimeStep = settings.getLastLogin() / totpTimeStep;
            //Check TOTP values for validity
            if (lastLoginTimeStep < 0) {
                debug.error("OATH.checkOTP() : invalid login time value : ");
                throw new AuthLoginException(amAuthOATH, "authFailed", null);
            }
            //must be greater than 0 or we get divide by 0, and cant be negative
            if (totpTimeStep <= 0) {
                debug.error("OATH.checkOTP() : invalid TOTP time step interval : ");
                throw new AuthLoginException(amAuthOATH, "authFailed", null);
            }
            if (totpStepsInWindow < 0) {
                debug.error("OATH.checkOTP() : invalid TOTP steps in window value : ");
                throw new AuthLoginException(amAuthOATH, "authFailed", null);
            }
            //get Time Step
            long localTime = (time / totpTimeStep) + (settings.getClockDriftSeconds() / totpTimeStep);
            if (lastLoginTimeStep == localTime) {
                debug.error("OATH.checkOTP(): Login failed attempting to use the same OTP in same Time Step: " + localTime);
                throw new InvalidPasswordException(amAuthOATH, "authFailed", null, userName, null);
            }
            boolean sameWindow = false;
            if (lastLoginTimeStep >= (localTime - totpStepsInWindow) && lastLoginTimeStep <= (localTime + totpStepsInWindow)) {
                if (debug.messageEnabled()) {
                    debug.message("OATH.checkOTP() : Logging in in the same TOTP window");
                }
                sameWindow = true;
            }
            String passLenStr = Integer.toString(passLen);
            otpGen = TOTPAlgorithm.generateTOTP(secretKey, Long.toHexString(localTime), passLenStr);
            if (isEqual(otpGen, otp)) {
                setLoginTime(id, localTime, settings);
                return true;
            }
            for (int i = 1; i <= totpStepsInWindow; i++) {
                long time1 = localTime + i;
                long time2 = localTime - i;
                //check time step after current time
                otpGen = TOTPAlgorithm.generateTOTP(secretKey, Long.toHexString(time1), passLenStr);
                if (isEqual(otpGen, otp)) {
                    setLoginTime(id, time1, settings);
                    return true;
                }
                //check time step before current time
                otpGen = TOTPAlgorithm.generateTOTP(secretKey, Long.toHexString(time2), passLenStr);
                if (isEqual(otpGen, otp) && sameWindow) {
                    debug.error("OATH.checkOTP() : Logging in in the same window with a OTP that is older " + "than the current times OTP");
                    return false;
                } else if (isEqual(otpGen, otp) && !sameWindow) {
                    setLoginTime(id, time2, settings);
                    return true;
                }
            }
        } else {
            debug.error("OATH.checkOTP() : No OTP algorithm selected");
            throw new AuthLoginException(amAuthOATH, "authFailed", null);
        }
    } catch (AuthLoginException e) {
        // Re-throw to avoid the catch-all block below that would log and lose the error message.
        throw e;
    } catch (Exception e) {
        debug.error("OATH.checkOTP() : checkOTP process failed : ", e);
        throw new AuthLoginException(amAuthOATH, "authFailed", null);
    }
    return false;
}
Also used : AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) IdRepoException(com.sun.identity.idm.IdRepoException) SMSException(com.sun.identity.sm.SMSException) DecoderException(org.apache.commons.codec.DecoderException) IOException(java.io.IOException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) SSOException(com.iplanet.sso.SSOException)

Example 9 with InvalidPasswordException

use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.

the class Application method authenticateToLDAP.

private ModuleState authenticateToLDAP(String userName, String userPassword) throws AuthLoginException {
    if (debug.messageEnabled()) {
        debug.message("In authenticateToLDAP with User : " + userName);
    }
    try {
        if (isSuperAdmin(userName)) {
            String baseDN = CollectionHelper.getServerMapAttr(currentConfig, ISAuthConstants.LDAP_BASEDN);
            ldapUtil = new LDAPAuthUtils(Collections.singleton(AuthD.directoryHostName + ":" + AuthD.directoryPort), Collections.<String>emptySet(), ldapSSL, AMResourceBundleCache.getInstance().getResBundle(amAuthApplication, getLoginLocale()), baseDN, debug);
            ldapUtil.authenticateUser(userName, userPassword);
            if (ldapUtil.getState() == ModuleState.SUCCESS) {
                userTokenId = userName;
            } else {
                debug.message("Invalid adminID or admin Password");
                setFailureID(ldapUtil.getUserId(userName));
                throw new AuthLoginException(amAuthApplication, "InvalidUP", null);
            }
        } else {
            if (initLDAPAttributes(ISAuthConstants.LDAP_SERVICE_NAME)) {
                ldapUtil.authenticateUser(userName, userPassword);
            } else {
                debug.message("Invalid userID or user Password");
                setFailureID(userName);
                throw new AuthLoginException(amAuthApplication, "basicLDAPex", null);
            }
        }
        return ldapUtil.getState();
    } catch (LDAPUtilException ex) {
        setFailureID(userName);
        if (ResultCode.NO_SUCH_OBJECT.equals(ex.getResultCode())) {
            debug.message("The specified user does not exist.");
            throw new AuthLoginException(amAuthApplication, "NoUser", null);
        } else if (ResultCode.INVALID_CREDENTIALS.equals(ex.getResultCode())) {
            debug.message("Invalid password.");
            String failureUserID = ldapUtil.getUserId();
            throw new InvalidPasswordException(amAuthApplication, "InvalidUP", null, failureUserID, ex);
        } else {
            throw new AuthLoginException(amAuthApplication, "basicLDAPex", null);
        }
    }
}
Also used : LDAPAuthUtils(org.forgerock.openam.ldap.LDAPAuthUtils) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) LDAPUtilException(org.forgerock.openam.ldap.LDAPUtilException)

Example 10 with InvalidPasswordException

use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.

the class DataStore method process.

public int process(Callback[] callbacks, int state) throws AuthLoginException {
    currentState = state;
    int retVal = 0;
    Callback[] idCallbacks = new Callback[2];
    try {
        if (currentState == ISAuthConstants.LOGIN_START) {
            if (callbacks != null && callbacks.length == 0) {
                userName = (String) sharedState.get(getUserKey());
                userPassword = (String) sharedState.get(getPwdKey());
                if (userName == null || userPassword == null) {
                    return ISAuthConstants.LOGIN_START;
                }
                NameCallback nameCallback = new NameCallback("dummy");
                nameCallback.setName(userName);
                idCallbacks[0] = nameCallback;
                PasswordCallback passwordCallback = new PasswordCallback("dummy", false);
                passwordCallback.setPassword(userPassword.toCharArray());
                idCallbacks[1] = passwordCallback;
            } else {
                idCallbacks = callbacks;
                //callbacks is not null
                userName = ((NameCallback) callbacks[0]).getName();
                char[] password = ((PasswordCallback) callbacks[1]).getPassword();
                userPassword = password == null ? null : String.valueOf(password);
            }
            if (userName == null) {
                debug.message("DataStore.process: Username is null/empty");
                throw new UserNamePasswordValidationException("amAuth", "InvalidUP", null);
            }
            if (userPassword == null || userPassword.length() == 0) {
                debug.message("DataStore.process: Password is null/empty");
                throw new InvalidPasswordException("amAuth", "invalidPasswd", null);
            }
            //store username password both in success and failure case
            storeUsernamePasswd(userName, userPassword);
            /*
                Fix for OPENAM-1872. Reject usernames with illegal characters (e.g. * or ! or ) or ( or & ), just
                like the LDAP LoginModule does. List of invalid characters comes from a new configuration entry (though
                the list of illegal characters does not seem to be processed in validateUserName). I want the invocation
                to be just like the LDAP LoginModule, and to handle the case in which the username format validator
                cannot be successfully loaded in validateUserName.
                 */
            validateUserName(userName, CollectionHelper.getMapAttr(currentConfig, INVALID_CHARS));
            AMIdentityRepository idrepo = getAMIdentityRepository(getRequestOrg());
            boolean success = idrepo.authenticate(idCallbacks);
            if (success) {
                retVal = ISAuthConstants.LOGIN_SUCCEED;
                validatedUserID = userName;
            } else {
                throw new AuthLoginException(amAuthDataStore, "authFailed", null);
            }
        } else {
            setFailureID(userName);
            throw new AuthLoginException(amAuthDataStore, "authFailed", null);
        }
    } catch (IdRepoException ex) {
        debug.message("idRepo Exception");
        setFailureID(userName);
        throw new AuthLoginException(amAuthDataStore, "authFailed", null, ex);
    }
    return retVal;
}
Also used : UserNamePasswordValidationException(com.sun.identity.authentication.spi.UserNamePasswordValidationException) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) IdRepoException(com.sun.identity.idm.IdRepoException) PasswordCallback(javax.security.auth.callback.PasswordCallback) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException)

Aggregations

InvalidPasswordException (com.sun.identity.authentication.spi.InvalidPasswordException)18 AuthLoginException (com.sun.identity.authentication.spi.AuthLoginException)15 PasswordCallback (javax.security.auth.callback.PasswordCallback)8 SSOException (com.iplanet.sso.SSOException)6 IdRepoException (com.sun.identity.idm.IdRepoException)6 NameCallback (javax.security.auth.callback.NameCallback)6 IOException (java.io.IOException)4 HashSet (java.util.HashSet)4 Set (java.util.Set)4 Callback (javax.security.auth.callback.Callback)4 HashMap (java.util.HashMap)3 LoginException (javax.security.auth.login.LoginException)3 LDAPUtilException (org.forgerock.openam.ldap.LDAPUtilException)3 SSOToken (com.iplanet.sso.SSOToken)2 AuthErrorCodeException (com.sun.identity.authentication.spi.AuthErrorCodeException)2 UserNamePasswordValidationException (com.sun.identity.authentication.spi.UserNamePasswordValidationException)2 AMIdentityRepository (com.sun.identity.idm.AMIdentityRepository)2 Map (java.util.Map)2 InternalSession (com.iplanet.dpro.session.service.InternalSession)1 NotificationSet (com.iplanet.services.comm.share.NotificationSet)1