Search in sources :

Example 6 with AuthLoginException

use of com.sun.identity.authentication.spi.AuthLoginException 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 7 with AuthLoginException

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

the class AuthContextLocal method abort.

/**
     * Terminates an ongoing <code>login</code> call that has not yet completed.
     *
     * @throws AuthLoginException if an error occurred during abort.
     *
     * @supported.api
     */
public void abort() throws AuthLoginException {
    authDebug.message("AuthContextLocal::abort()");
    try {
        amlc.abort();
    } catch (Exception e) {
        if (authDebug.messageEnabled()) {
            authDebug.message("Exception in AMLoginContext::abort() " + e.getMessage());
        }
        throw new AuthLoginException(amAuthContextLocal, "abortError", null, e);
    }
    loginStatus = AuthContext.Status.COMPLETED;
}
Also used : AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) PolicyException(com.sun.identity.policy.PolicyException)

Example 8 with AuthLoginException

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

the class AuthContextLocal method login.

/**
     * Performs the Login for the given AuthContext
     * @param type authentication index type
     * @param indexName authentication index name
     * @param principal principal name of the user to be authenticated
     * @param password password for the user
     * @param subject authentication subject
     * @param envMap Environment map, this is applicable only when the type
     *        is <code>AuthContext.IndexType.RESOURCE</code>
     * @param locale locale setting
     * @throws AuthLoginException if error occurs during login
     */
protected void login(AuthContext.IndexType type, String indexName, Principal principal, char[] password, Subject subject, Map envMap, String locale) throws AuthLoginException {
    try {
        /*if (!getStatus().equals(AuthContext.Status.NOT_STARTED)) {
                if (authDebug.messageEnabled()) {
                    authDebug.message("AuthContextLocal::login called " +
                    "when the current login status is : " + getStatus());
                }
                throw new AuthLoginException(amAuthContextLocal, 
                    "invalidMethod", new Object[]{getStatus()});
            }*/
        // switch the login status
        loginStatus = AuthContext.Status.IN_PROGRESS;
        String redirectUrl = null;
        // specially processing for resouce/IP/Environement based auth
        if ((type != null) && type.equals(AuthContext.IndexType.RESOURCE)) {
            // this is resouce/IP/Env based authentication
            // call Policy Decision Util to find out the actual auth type 
            // required by policy
            List result = Collections.EMPTY_LIST;
            try {
                result = PolicyDecisionUtils.doResourceIPEnvAuth(indexName, organizationName, envMap);
            } catch (PolicyException pe) {
                // ignore, continue to default realm based authentication
                // may need to revisit this in the future
                authDebug.warning("AuthContextLocal.login() policy error " + "indexName=" + indexName, pe);
                type = null;
                indexName = null;
            }
            if (authDebug.messageEnabled()) {
                authDebug.message("AuthContextLocal.login: policy decision=" + result);
            }
            if (result.size() == 2) {
                type = (AuthContext.IndexType) result.get(0);
                indexName = (String) result.get(1);
            } else if (result.size() == 1) {
                // this is the redirection case (Policy Redirection Advice)
                redirectUrl = (String) result.get(0);
                // append goto parameter for federation case
                Set tmp = (Set) envMap.get(ISAuthConstants.GOTO_PARAM);
                if ((tmp != null) && !tmp.isEmpty()) {
                    String gotoParam = (String) tmp.iterator().next();
                    if ((gotoParam != null) && (gotoParam.length() != 0)) {
                        if ((redirectUrl != null) && (redirectUrl.indexOf("?") != -1)) {
                            redirectUrl = redirectUrl + "&" + ISAuthConstants.GOTO_PARAM + "=" + URLEncDec.encode(gotoParam);
                        } else {
                            redirectUrl = redirectUrl + "?" + ISAuthConstants.GOTO_PARAM + "=" + URLEncDec.encode(gotoParam);
                        }
                    }
                }
                type = null;
                indexName = null;
            } else {
                // no policy decision, use default realm login
                type = null;
                indexName = null;
            }
        }
        HashMap loginParamsMap = new HashMap();
        loginParamsMap.put(INDEX_TYPE, type);
        loginParamsMap.put(INDEX_NAME, indexName);
        loginParamsMap.put(PRINCIPAL, principal);
        loginParamsMap.put(PASSWORD, password);
        loginParamsMap.put(SUBJECT, subject);
        loginParamsMap.put(LOCALE, locale);
        if (redirectUrl != null) {
            loginParamsMap.put(REDIRECT_URL, redirectUrl);
        }
        if (authDebug.messageEnabled()) {
            authDebug.message("loginParamsMap : " + loginParamsMap.toString());
        }
        authDebug.message("calling AMLoginContext::exceuteLogin : ");
        amlc.executeLogin(loginParamsMap);
        authDebug.message("after AMLoginContext::exceuteLogin : ");
        if (amlc.getStatus() == LoginStatus.AUTH_SUCCESS) {
            loginStatus = AuthContext.Status.SUCCESS;
        } else if (amlc.getStatus() == LoginStatus.AUTH_FAILED) {
            loginStatus = AuthContext.Status.FAILED;
        }
        if (authDebug.messageEnabled()) {
            authDebug.message("Status at the end of login() : " + loginStatus);
        }
    } catch (AuthLoginException e) {
        if (authDebug.messageEnabled()) {
            authDebug.message("Exception in ac.login : " + e.toString());
        }
        throw e;
    }
}
Also used : Set(java.util.Set) PolicyException(com.sun.identity.policy.PolicyException) HashMap(java.util.HashMap) AuthContext(com.sun.identity.authentication.AuthContext) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) ArrayList(java.util.ArrayList) List(java.util.List)

Example 9 with AuthLoginException

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

the class AuthXMLHandler method processAuthXMLRequest.

/*
     * Process the XMLRequest
     */
private AuthXMLResponse processAuthXMLRequest(String xml, PLLAuditor auditor, AuthXMLRequest authXMLRequest, HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
    if (messageEnabled) {
        debug.message("authXMLRequest is : " + authXMLRequest);
    }
    int requestType = authXMLRequest.getRequestType();
    String sessionID = authXMLRequest.getAuthIdentifier();
    String orgName = authXMLRequest.getOrgName();
    AuthContextLocal authContext = authXMLRequest.getAuthContext();
    LoginState loginState = AuthUtils.getLoginState(authContext);
    auditor.setMethod(getMethodName(requestType));
    auditor.setUserId(getAuthenticationId(loginState));
    auditor.setTrackingId(getContextId(loginState));
    auditor.setRealm(orgName);
    auditor.auditAccessAttempt();
    String params = authXMLRequest.getParams();
    List envList = authXMLRequest.getEnvironment();
    Map envMap = toEnvMap(envList);
    AuthXMLResponse authResponse = new AuthXMLResponse(requestType);
    authResponse.setAuthContext(authContext);
    authResponse.setAuthIdentifier(sessionID);
    if (messageEnabled) {
        debug.message("authContext is : " + authContext);
        debug.message("requestType : " + requestType);
    }
    if (authXMLRequest.getValidSessionNoUpgrade()) {
        authResponse.setAuthXMLRequest(authXMLRequest);
        authResponse.setValidSessionNoUpgrade(true);
        return authResponse;
    }
    String securityEnabled = null;
    try {
        securityEnabled = AuthUtils.getRemoteSecurityEnabled();
    } catch (AuthException auExp) {
        debug.error("Got Exception", auExp);
        setErrorCode(authResponse, auExp);
        return authResponse;
    }
    if (debug.messageEnabled()) {
        debug.message("Security Enabled = " + securityEnabled);
    }
    if (requestType != 0) {
        if ((securityEnabled != null) && (securityEnabled.equals("true"))) {
            security = true;
            String indexNameLoc = authXMLRequest.getIndexName();
            AuthContext.IndexType indexTypeLoc = authXMLRequest.getIndexType();
            if (indexTypeLoc == null) {
                indexTypeLoc = AuthUtils.getIndexType(authContext);
                indexNameLoc = AuthUtils.getIndexName(authContext);
            }
            if (debug.messageEnabled()) {
                debug.message("Index Name Local : " + indexNameLoc);
                debug.message("Index Type Local : " + indexTypeLoc);
            }
            if (((indexTypeLoc == null) || (indexNameLoc == null)) || !((indexTypeLoc == AuthContext.IndexType.MODULE_INSTANCE) && indexNameLoc.equals("Application"))) {
                try {
                    String ssoTokenID = authXMLRequest.getAppSSOTokenID();
                    if (debug.messageEnabled()) {
                        debug.message("Session ID = : " + ssoTokenID);
                    }
                    SSOTokenManager manager = SSOTokenManager.getInstance();
                    SSOToken appSSOToken = manager.createSSOToken(ssoTokenID);
                    // retry
                    if (!manager.isValidToken(appSSOToken)) {
                        if (debug.messageEnabled()) {
                            debug.message("App SSOToken is not valid");
                        }
                        setErrorCode(authResponse, new AuthException(AMAuthErrorCode.REMOTE_AUTH_INVALID_SSO_TOKEN, null));
                        return authResponse;
                    } else {
                        debug.message("App SSOToken is VALID");
                    }
                } catch (SSOException ssoe) {
                    // can retry
                    if (debug.messageEnabled()) {
                        debug.message("App SSOToken is not valid: " + ssoe.getMessage());
                    }
                    setErrorCode(authResponse, new AuthException(AMAuthErrorCode.REMOTE_AUTH_INVALID_SSO_TOKEN, null));
                    return authResponse;
                } catch (Exception exp) {
                    debug.error("Got Exception", exp);
                    setErrorCode(authResponse, exp);
                    return authResponse;
                }
            }
        }
    } else {
        security = false;
    }
    // selected choice then start module based authentication.
    if ((AuthUtils.getIndexType(authContext) == AuthContext.IndexType.LEVEL) || (AuthUtils.getIndexType(authContext) == AuthContext.IndexType.COMPOSITE_ADVICE)) {
        Callback[] callbacks = authXMLRequest.getSubmittedCallbacks();
        if (messageEnabled) {
            debug.message("Callbacks are  : " + callbacks);
        }
        if (callbacks != null) {
            if (messageEnabled) {
                debug.message("Callback length is : " + callbacks.length);
            }
            if (callbacks[0] instanceof ChoiceCallback) {
                ChoiceCallback cc = (ChoiceCallback) callbacks[0];
                int[] selectedIndexes = cc.getSelectedIndexes();
                int selected = selectedIndexes[0];
                String[] choices = cc.getChoices();
                String indexName = choices[selected];
                if (messageEnabled) {
                    debug.message("Selected Index is : " + indexName);
                }
                authXMLRequest.setIndexType("moduleInstance");
                authXMLRequest.setIndexName(indexName);
                authXMLRequest.setRequestType(AuthXMLRequest.LoginIndex);
                requestType = AuthXMLRequest.LoginIndex;
                auditor.setMethod(getMethodName(requestType));
            }
        }
    }
    AuthContext.Status loginStatus = AuthContext.Status.IN_PROGRESS;
    HttpServletRequest clientRequest = authXMLRequest.getClientRequest();
    if (loginState != null) {
        loginState.setHttpServletRequest(clientRequest);
        loginState.setHttpServletResponse(authXMLRequest.getClientResponse());
        if (clientRequest != null) {
            loginState.setParamHash(AuthUtils.parseRequestParameters(clientRequest));
        }
    }
    switch(requestType) {
        case AuthXMLRequest.NewAuthContext:
            try {
                processNewRequest(servletRequest, servletResponse, authResponse, loginState, authContext);
                postProcess(loginState, authResponse);
            } catch (Exception ex) {
                debug.error("Error in NewAuthContext ", ex);
                setErrorCode(authResponse, ex);
            }
            break;
        case AuthXMLRequest.Login:
            try {
                if (sessionID != null && sessionID.equals("0")) {
                    processNewRequest(servletRequest, servletResponse, authResponse, loginState, authContext);
                }
                String clientHost = null;
                if (security) {
                    clientHost = authXMLRequest.getHostName();
                    if (messageEnabled) {
                        debug.message("Client Host from Request = " + clientHost);
                    }
                }
                if ((clientHost == null) && (servletRequest != null)) {
                    clientHost = ClientUtils.getClientIPAddress(servletRequest);
                }
                loginState.setClient(clientHost);
                authContext.login();
                //setServletRequest(servletRequest,authContext);
                processRequirements(xml, authContext, authResponse, params, servletRequest);
                loginStatus = authContext.getStatus();
                authResponse.setRemoteRequest(loginState.getHttpServletRequest());
                authResponse.setRemoteResponse(loginState.getHttpServletResponse());
                postProcess(loginState, authResponse);
                checkACException(authResponse, authContext);
            } catch (Exception ex) {
                debug.error("Error during login ", ex);
                setErrorCode(authResponse, ex);
                authResponse.setLoginStatus(authContext.getStatus());
            }
            break;
        case AuthXMLRequest.LoginIndex:
            try {
                AuthContext.IndexType indexType = authXMLRequest.getIndexType();
                String indexName = authXMLRequest.getIndexName();
                if (messageEnabled) {
                    debug.message("indexName is : " + indexName);
                    debug.message("indexType is : " + indexType);
                }
                if (sessionID != null && sessionID.equals("0")) {
                    processNewRequest(servletRequest, servletResponse, authResponse, loginState, authContext);
                }
                String clientHost = null;
                if (security) {
                    clientHost = authXMLRequest.getHostName();
                    if (messageEnabled) {
                        debug.message("Client Host from Request = " + clientHost);
                    }
                }
                if ((clientHost == null) && (servletRequest != null)) {
                    clientHost = ClientUtils.getClientIPAddress(servletRequest);
                }
                loginState.setClient(clientHost);
                String locale = authXMLRequest.getLocale();
                if (locale != null && locale.length() > 0) {
                    if (debug.messageEnabled()) {
                        debug.message("locale is : " + locale);
                    }
                    authContext.login(indexType, indexName, envMap, locale);
                } else {
                    authContext.login(indexType, indexName, envMap, null);
                }
                //setServletRequest(servletRequest,authContext);
                processRequirements(xml, authContext, authResponse, params, servletRequest);
                loginStatus = authContext.getStatus();
                authResponse.setRemoteRequest(loginState.getHttpServletRequest());
                authResponse.setRemoteResponse(loginState.getHttpServletResponse());
                postProcess(loginState, authResponse);
                checkACException(authResponse, authContext);
            } catch (Exception ex) {
                debug.error("Exception during LoginIndex", ex);
                setErrorCode(authResponse, ex);
            }
            break;
        case AuthXMLRequest.LoginSubject:
            try {
                Subject subject = authXMLRequest.getSubject();
                authContext.login(subject);
                //setServletRequest(servletRequest,authContext);
                processRequirements(xml, authContext, authResponse, params, servletRequest);
                postProcess(loginState, authResponse);
                loginStatus = authContext.getStatus();
                checkACException(authResponse, authContext);
            } catch (AuthLoginException ale) {
                debug.error("Exception during LoginSubject", ale);
                setErrorCode(authResponse, ale);
            }
            break;
        case AuthXMLRequest.SubmitRequirements:
            try {
                //setServletRequest(servletRequest,authContext);
                Callback[] submittedCallbacks = authXMLRequest.getSubmittedCallbacks();
                authContext.submitRequirements(submittedCallbacks);
                Callback[] reqdCallbacks = null;
                if (authContext.hasMoreRequirements()) {
                    reqdCallbacks = authContext.getRequirements();
                    authResponse.setReqdCallbacks(reqdCallbacks);
                }
                authResponse.setRemoteRequest(loginState.getHttpServletRequest());
                authResponse.setRemoteResponse(loginState.getHttpServletResponse());
                postProcess(loginState, authResponse);
                loginStatus = authContext.getStatus();
                authResponse.setLoginStatus(loginStatus);
                InternalSession oldSession = loginState.getOldSession();
                authResponse.setOldSession(oldSession);
                checkACException(authResponse, authContext);
            } catch (Exception ex) {
                debug.error("Error during submit requirements ", ex);
                setErrorCode(authResponse, ex);
            }
            break;
        case AuthXMLRequest.QueryInformation:
            try {
                if (sessionID != null && sessionID.equals("0")) {
                    processNewRequest(servletRequest, servletResponse, authResponse, loginState, authContext);
                }
                Set moduleNames = authContext.getModuleInstanceNames();
                authResponse.setModuleNames(moduleNames);
                authResponse.setAuthContext(authContext);
                postProcess(loginState, authResponse);
                checkACException(authResponse, authContext);
            } catch (Exception ex) {
                debug.error("Error during Query Information", ex);
                setErrorCode(authResponse, ex);
            }
            break;
        case AuthXMLRequest.Logout:
            //boolean logoutCalled = false;
            if (sessionID != null && !sessionID.equals("0")) {
                /*intSess = AuthD.getSession(sessionID);
                    try {
                        token = SSOTokenManager.getInstance().
                            createSSOToken(sessionID);
                        if (debug.messageEnabled()) {
                            debug.message("AuthXMLHandler."
                                + "processAuthXMLRequest: Created token " 
                                + "during logout = "+token);
                        }
	            } catch (com.iplanet.sso.SSOException ssoExp) {
                       if (debug.messageEnabled()) {
		           debug.message("AuthXMLHandler.processAuthXMLRequest:"
                           + "SSOException checking validity of SSO Token");
                       }
	            }*/
                try {
                    AuthUtils.logout(sessionID, servletRequest, servletResponse);
                } catch (com.iplanet.sso.SSOException ssoExp) {
                    if (debug.messageEnabled()) {
                        debug.message("AuthXMLHandler.processAuthXMLRequest:" + "SSOException checking validity of SSO Token");
                    }
                }
            }
            /*if (intSess != null) {
                    loginContext = intSess.getObject(ISAuthConstants.
                        LOGIN_CONTEXT);
                }
                try {
                    if (loginContext != null) {
                        if (loginContext instanceof 
                            javax.security.auth.login.LoginContext) {
                            javax.security.auth.login.LoginContext lc = 
                                (javax.security.auth.login.LoginContext) 
                                 loginContext;
                            lc.logout();
                        } else {
                            com.sun.identity.authentication.jaas.LoginContext 
                                jlc = (com.sun.identity.authentication.jaas.
                                LoginContext) loginContext;
                            jlc.logout();
                        }
                        logoutCalled = true;
                    }
                } catch (javax.security.auth.login.LoginException loginExp) {
                    debug.error("AuthXMLHandler.processAuthXMLRequest: "
                        + "Cannot Execute module Logout", loginExp);
                }
                Set postAuthSet = null;
                if (intSess != null) {
                    postAuthSet = (Set) intSess.getObject(ISAuthConstants.
                        POSTPROCESS_INSTANCE_SET);
                }
                if ((postAuthSet != null) && !(postAuthSet.isEmpty())) {
                    AMPostAuthProcessInterface postLoginInstance=null;
                    for(Iterator iter = postAuthSet.iterator();
                    iter.hasNext();) {
                        try {
	                    postLoginInstance =
	 	                (AMPostAuthProcessInterface) iter.next();
                             postLoginInstance.onLogout(servletRequest, 
                                 servletResponse, token);
                        } catch (Exception exp) {
                           debug.error("AuthXMLHandler.processAuthXMLRequest: "
                               + "Failed in post logout.", exp);
                        }
	            }
                } else {
                    String plis = null;
                    if (intSess != null) {
                        plis = intSess.getProperty(
                            ISAuthConstants.POST_AUTH_PROCESS_INSTANCE);
                    }
                    if (plis != null && plis.length() > 0) {
                        StringTokenizer st = new StringTokenizer(plis, "|");
                        if (token != null) {
                            while (st.hasMoreTokens()) {
                                String pli = (String)st.nextToken();
                                try {
                                    AMPostAuthProcessInterface postProcess = 
                                            (AMPostAuthProcessInterface)
                                            Thread.currentThread().
                                            getContextClassLoader().
                                            loadClass(pli).newInstance();
                                    postProcess.onLogout(servletRequest, 
                                        servletResponse, token);
                                } catch (Exception e) {
                                    debug.error("AuthXMLHandler."
                                        + "processAuthXMLRequest:" + pli, e);
                                }
                            }
                        }
                    }
                }
                try {
                    boolean isTokenValid = SSOTokenManager.getInstance().
                        isValidToken(token);
                    if ((token != null) && isTokenValid) {
                        AuthD.getAuth().logLogout(token);
                        Session session = Session.getSession(
                            new SessionID(sessionID));
                        session.logout();
                        debug.message("logout successful.");
                    }
	        } catch (com.iplanet.dpro.session.SessionException 
                    sessExp) {
                    if (debug.messageEnabled()) {
                        debug.message("AuthXMLHandler."
                            + "processAuthXMLRequest: SessionException"
                            + " checking validity of SSO Token");
                    }
	        } catch (com.iplanet.sso.SSOException ssoExp) {
                    if (debug.messageEnabled()) {
                        debug.message("AuthXMLHandler."
                            + "processAuthXMLRequest: SSOException "
                            + "checking validity of SSO Token");
                    }
                }*/
            authResponse.setLoginStatus(AuthContext.Status.COMPLETED);
            break;
        case AuthXMLRequest.Abort:
            try {
                authContext.abort();
                loginStatus = authContext.getStatus();
                authResponse.setLoginStatus(loginStatus);
                checkACException(authResponse, authContext);
            } catch (AuthLoginException ale) {
                debug.error("Error aborting ", ale);
                setErrorCode(authResponse, ale);
            }
            break;
    }
    if (messageEnabled) {
        debug.message("loginStatus: " + loginStatus);
        if (authContext != null) {
            debug.message("error Code: " + authContext.getErrorCode());
            debug.message("error Template: " + authContext.getErrorTemplate());
        }
    }
    if (loginStatus == AuthContext.Status.FAILED) {
        if ((authContext.getErrorMessage() != null) && (authContext.getErrorMessage().equals(AMResourceBundleCache.getInstance().getResBundle("amAuthLDAP", com.sun.identity.shared.locale.Locale.getLocale(loginState.getLocale())).getString(ISAuthConstants.EXCEED_RETRY_LIMIT)))) {
            loginState.setErrorCode(AMAuthErrorCode.AUTH_LOGIN_FAILED);
        }
        if ((authContext.getErrorCode() != null) && ((authContext.getErrorCode()).length() > 0)) {
            authResponse.setErrorCode(authContext.getErrorCode());
        }
        checkACException(authResponse, authContext);
        if ((authContext.getErrorTemplate() != null) && ((authContext.getErrorTemplate()).length() > 0)) {
            authResponse.setErrorTemplate(authContext.getErrorTemplate());
        }
        //Account Lockout Warning Check
        if ((authContext.getErrorCode() != null) && (authContext.getErrorCode().equals(AMAuthErrorCode.AUTH_INVALID_PASSWORD))) {
            String lockWarning = authContext.getLockoutMsg();
            if ((lockWarning != null) && (lockWarning.length() > 0)) {
                authResponse.setErrorMessage(lockWarning);
            }
        }
    }
    auditor.setUserId(getAuthenticationId(loginState));
    auditor.setTrackingId(getContextId(loginState));
    return authResponse;
}
Also used : SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) ResponseSet(com.iplanet.services.comm.share.ResponseSet) HashSet(java.util.HashSet) RequestSet(com.iplanet.services.comm.share.RequestSet) AuthException(com.sun.identity.authentication.service.AuthException) AuthContext(com.sun.identity.authentication.AuthContext) SSOException(com.iplanet.sso.SSOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) InternalSession(com.iplanet.dpro.session.service.InternalSession) List(java.util.List) ArrayList(java.util.ArrayList) SSOTokenManager(com.iplanet.sso.SSOTokenManager) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException) AuthException(com.sun.identity.authentication.service.AuthException) Subject(javax.security.auth.Subject) ChoiceCallback(javax.security.auth.callback.ChoiceCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) Callback(javax.security.auth.callback.Callback) X509CertificateCallback(com.sun.identity.authentication.spi.X509CertificateCallback) ChoiceCallback(javax.security.auth.callback.ChoiceCallback) NameCallback(javax.security.auth.callback.NameCallback) LoginState(com.sun.identity.authentication.service.LoginState) SSOException(com.iplanet.sso.SSOException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 10 with AuthLoginException

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

the class AuthXMLHandler method checkACException.

/*
     * Check for the AuthContext Exceptions
     */
private void checkACException(AuthXMLResponse authResponse, AuthContextLocal acl) {
    AuthLoginException ale = acl.getLoginException();
    if (ale == null) {
        return;
    }
    /*
         * this code does not allow client to remotely select locale.
         * but this is a problem comes with the AuthContext API, cannot
         * be simply solved here.
         */
    if ((ale.getL10NMessage(locale) != null) && ((ale.getL10NMessage(locale)).length() > 0)) {
        authResponse.setErrorMessage(ale.getL10NMessage(locale));
    }
    authResponse.setIsException(true);
}
Also used : AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException)

Aggregations

AuthLoginException (com.sun.identity.authentication.spi.AuthLoginException)118 SSOException (com.iplanet.sso.SSOException)39 Callback (javax.security.auth.callback.Callback)29 IdRepoException (com.sun.identity.idm.IdRepoException)27 InvalidPasswordException (com.sun.identity.authentication.spi.InvalidPasswordException)25 NameCallback (javax.security.auth.callback.NameCallback)24 PasswordCallback (javax.security.auth.callback.PasswordCallback)23 IOException (java.io.IOException)20 Set (java.util.Set)18 HttpServletRequest (javax.servlet.http.HttpServletRequest)15 SSOToken (com.iplanet.sso.SSOToken)14 HashMap (java.util.HashMap)14 AuthContext (com.sun.identity.authentication.AuthContext)13 Map (java.util.Map)12 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)12 Test (org.testng.annotations.Test)12 HashSet (java.util.HashSet)9 LoginException (javax.security.auth.login.LoginException)8 SSOTokenManager (com.iplanet.sso.SSOTokenManager)7 AuthException (com.sun.identity.authentication.service.AuthException)7