Search in sources :

Example 31 with SSOTokenManager

use of com.iplanet.sso.SSOTokenManager 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 32 with SSOTokenManager

use of com.iplanet.sso.SSOTokenManager in project OpenAM by OpenRock.

the class SessionUtils method checkPermissionToSetProperty.

/**
     * Helper method to check if client has taken permission to
     * set value to it. If
     * @param clientToken Token of the client setting protected property.
     * @param key Property key
     * @param value Property value.
     * @throws SessionException if the key is protected property.
     */
public static void checkPermissionToSetProperty(SSOToken clientToken, String key, String value) throws SessionException {
    Debug sessionDebug = InjectorHolder.getInstance(Key.get(Debug.class, Names.named(SESSION_DEBUG)));
    if (InternalSession.isProtectedProperty(key)) {
        if (clientToken == null) {
            // Throw Ex. Client should identify itself.
            if (sessionDebug.warningEnabled()) {
                sessionDebug.warning("SessionUtils.checkPermissionToSetProperty(): " + "Attempt to set protected property without client " + "token [" + key + "=" + value + "]");
            }
            throw new SessionException(SessionBundle.getString("protectedPropertyNoClientToken") + " " + key);
        }
        SSOTokenManager ssoTokenManager = null;
        try {
            ssoTokenManager = SSOTokenManager.getInstance();
        } catch (SSOException ssoEx) {
            // Throw Ex. Not able to get SSOTokenManager instance.
            sessionDebug.error("SessionUtils.checkPermissionToSetProperty(): " + "Cannot get instance of SSOTokenManager.");
            throw new SessionException(SessionBundle.getString("protectedPropertyNoSSOTokenMgrInstance") + " " + key);
        }
        if (!ssoTokenManager.isValidToken(clientToken)) {
            // Throw Ex. Client should identify itself.
            if (sessionDebug.warningEnabled()) {
                sessionDebug.warning("SessionUtils.checkPermissionToSetProperty(): " + "Attempt to set protected property with invalid client" + " token [" + key + "=" + value + "]");
            }
            throw new SessionException(SessionBundle.getString("protectedPropertyInvalidClientToken") + " " + key);
        }
        SSOToken admToken = null;
        try {
            admToken = SessionUtils.getAdminToken();
        } catch (SSOException ssoEx) {
            // Throw Ex. Server not able to get Admin Token.
            sessionDebug.error("SessionUtils.checkPermissionToSetProperty(): " + "Cannot get Admin Token for validation to set protected " + "property [" + key + "=" + value + "]");
            throw new SessionException(SessionBundle.getString("protectedPropertyNoAdminToken") + " " + key);
        }
        if (!SessionUtils.isAdmin(admToken, clientToken)) {
            // Throw Ex. Client not authorized to set this property.
            sessionDebug.error("SessionUtils.checkPermissionToSetProperty(): " + "Client does not have permission to set protected " + "property" + key + "=" + value + "]");
            throw new SessionException(SessionBundle.getString("protectedPropertyNoPermission") + " " + key);
        }
    }
}
Also used : SSOTokenManager(com.iplanet.sso.SSOTokenManager) SSOToken(com.iplanet.sso.SSOToken) SessionException(com.iplanet.dpro.session.SessionException) SSOException(com.iplanet.sso.SSOException) Debug(com.sun.identity.shared.debug.Debug)

Example 33 with SSOTokenManager

use of com.iplanet.sso.SSOTokenManager in project OpenAM by OpenRock.

the class AMLoginContext method processIndexType.

/* do the required process for different indextypes
     * return true if needs to return back
     * false if needs to continue
     * Exception if error
     */
boolean processIndexType(IndexType indexType, String indexName, String orgDN) throws AuthLoginException {
    boolean ignoreProfile = false;
    IndexType previousType = loginState.getPreviousIndexType();
    /*
         * Throw an exception if org specified in query does not match org specified in authContext/loginState
         *
         * (unless previous index type was LEVEL or COMPOSITE_ADVICE, or current index type is MODULE_INSTANCE)
         */
    String normOrgDN = DNUtils.normalizeDN(orgDN);
    if ((previousType != IndexType.LEVEL && previousType != IndexType.COMPOSITE_ADVICE) || indexType != IndexType.MODULE_INSTANCE) {
        // proceed only when the org in the auth context matches
        // that in the query. otherwise it means a call with a new org.
        HttpServletRequest hreq = loginState.getHttpServletRequest();
        boolean isTokenValid = false;
        final boolean isFederation = indexType == IndexType.MODULE_INSTANCE && ISAuthConstants.FEDERATION_MODULE.equals(indexName);
        if (hreq != null && !isFederation) {
            try {
                SSOTokenManager manager = SSOTokenManager.getInstance();
                SSOToken ssoToken = manager.createSSOToken(hreq);
                if (manager.isValidToken(ssoToken)) {
                    debug.message("Existing Valid session");
                    isTokenValid = true;
                }
            } catch (Exception e) {
                debug.message("ERROR processIndexType/SSOToken validation - " + e.toString());
            }
            if (!isTokenValid) {
                debug.message("No existing valid session");
                Hashtable requestHash = loginState.getRequestParamHash();
                String newOrgDN = AuthUtils.getDomainNameByRequest(hreq, requestHash);
                if (debug.messageEnabled()) {
                    debug.message("orgDN from existing auth context: " + orgDN + ", orgDN from query string: " + newOrgDN);
                }
                if (normOrgDN != null) {
                    if (!normOrgDN.equals(newOrgDN)) {
                        loginStatus.setStatus(LoginStatus.AUTH_RESET);
                        loginState.setErrorCode(AMAuthErrorCode.AUTH_ERROR);
                        setErrorMsgAndTemplate();
                        internalAuthError = true;
                        throw new AuthLoginException(BUNDLE_NAME, AMAuthErrorCode.AUTH_ERROR, null);
                    }
                }
            }
        }
    }
    if (indexType == IndexType.COMPOSITE_ADVICE) {
        /*
             * Configure login following COMPOSITE_ADVICE
             */
        debug.message("IndexType is COMPOSITE_ADVICE");
        // Set the Composite Advice in Login State after decoding
        String compositeAdvice = URLEncDec.decode(indexName);
        loginState.setCompositeAdvice(compositeAdvice);
        // else continue with login process
        try {
            if (processCompositeAdvice(indexType, indexName, orgDN, clientType)) {
                debug.message("multiple modules found");
                return true;
            } else {
                return false;
            }
        } catch (AuthException ae) {
            // no modules configured
            loginState.setErrorCode(ae.getErrorCode());
            loginState.logFailed(ae.getMessage());
            auditor.auditLoginFailure(loginState);
            setErrorMsgAndTemplate();
            loginStatus.setStatus(LoginStatus.AUTH_FAILED);
            throw new AuthLoginException(ae);
        }
    } else if (indexType == IndexType.LEVEL) {
        /*
             * Configure login so that successful authentication achieve specified authentication LEVEL
             */
        debug.message("IndexType is level");
        // else continue with login process
        try {
            if (processLevel(indexType, indexName, orgDN, clientType)) {
                debug.message("multiple modules found");
                return true;
            } else {
                return false;
            }
        } catch (AuthException ae) {
            // no modules configured
            loginState.setErrorCode(ae.getErrorCode());
            loginState.logFailed(ae.getMessage());
            auditor.auditLoginFailure(loginState);
            setErrorMsgAndTemplate();
            loginStatus.setStatus(LoginStatus.AUTH_FAILED);
            throw new AuthLoginException(ae);
        }
    } else if (indexType == IndexType.USER) {
        /*
             * Configure login for specified user
             */
        debug.message("IndexType is user");
        // if user is not active throw exception
        // else continue with login
        boolean userValid = false;
        if (!loginState.ignoreProfile()) {
            userValid = validateUser(indexName);
        } else {
            ignoreProfile = true;
        }
        if ((!userValid) && (!ignoreProfile)) {
            debug.message("User is not active");
            loginState.logFailed(bundle.getString("userInactive"), "USERINACTIVE");
            auditor.auditLoginFailure(loginState, USER_INACTIVE);
            /* The user based authentication errors should not be different
                 * for users who exist and who don't, which can lead to
                 * possibility of enumerating existing users.
                 * The AMAuthErrorCode.AUTH_LOGIN_FAILED error code is used for
                 * all user based authentication errors.
                 * Refer issue3278
                 */
            loginState.setErrorCode(AMAuthErrorCode.AUTH_LOGIN_FAILED);
            setErrorMsgAndTemplate();
            //destroySession();
            loginStatus.setStatus(LoginStatus.AUTH_FAILED);
            throw new AuthLoginException(BUNDLE_NAME, AMAuthErrorCode.AUTH_USER_INACTIVE, null);
        } else if (ignoreProfile) {
            setAuthError(AMAuthErrorCode.AUTH_PROFILE_ERROR, "loginDenied");
            throw new AuthLoginException(BUNDLE_NAME, AMAuthErrorCode.AUTH_PROFILE_ERROR, null);
        } else {
            return false;
        }
    } else if (indexType == IndexType.MODULE_INSTANCE) {
        /*
             * Configure login for specified authentication module
             */
        // check if module exists in the allowed modules list
        debug.message("indexType is module");
        boolean instanceExists = loginState.getDomainAuthenticators().contains(indexName);
        if (!indexName.equals(ISAuthConstants.APPLICATION_MODULE) && !instanceExists) {
            debug.message("Module denied!!");
            loginState.setErrorCode(AMAuthErrorCode.AUTH_MODULE_DENIED);
            loginState.logFailed(bundle.getString("moduleDenied"), "MODULEDENIED");
            auditor.auditLoginFailure(loginState, MODULE_DENIED);
            setErrorMsgAndTemplate();
            loginStatus.setStatus(LoginStatus.AUTH_FAILED);
            throw new AuthLoginException(BUNDLE_NAME, AMAuthErrorCode.AUTH_MODULE_DENIED, null);
        } else {
            return false;
        }
    } else if (indexType == IndexType.ROLE) {
        /*
             * Configure login for specified role - No longer supported, throw an exception
             */
        debug.message("indexType is Role");
        if (loginState.ignoreProfile()) {
            setAuthError(AMAuthErrorCode.AUTH_TYPE_DENIED, "loginDenied");
            throw new AuthLoginException(BUNDLE_NAME, AMAuthErrorCode.AUTH_TYPE_DENIED, null);
        }
    }
    /*
         * IndexType not processed by this method
         */
    return false;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) SSOTokenManager(com.iplanet.sso.SSOTokenManager) SSOToken(com.iplanet.sso.SSOToken) Hashtable(java.util.Hashtable) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) IndexType(com.sun.identity.authentication.AuthContext.IndexType) 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)

Example 34 with SSOTokenManager

use of com.iplanet.sso.SSOTokenManager in project OpenAM by OpenRock.

the class AdminInterfaceUtils method initialize.

/**
     * Initializes the default containers using SMS
     */
private static void initialize() {
    if (!initialized) {
        try {
            // Generate a SSOToken to initialize ServiceSchemaManager
            String adminDN = (String) AccessController.doPrivileged(new AdminDNAction());
            String adminPassword = (String) AccessController.doPrivileged(new AdminPasswordAction());
            SSOTokenManager mgr = SSOTokenManager.getInstance();
            ServiceConfigManager scm = new ServiceConfigManager(SERVICE_NAME, mgr.createSSOToken(new AuthPrincipal(adminDN), adminPassword));
            if (!addedListener) {
                addedListener = true;
                scm.addListener(new AdminInterfaceUtils());
            }
            ServiceConfig globalConfig = scm.getGlobalConfig(null);
            ServiceConfig templatesConfig = globalConfig.getSubConfig(TEMPLATES);
            ServiceConfig structTemplateSubConfig = templatesConfig.getSubConfig(STRUCTURE_TEMPLATES);
            ServiceConfig groupContConfig = structTemplateSubConfig.getSubConfig(GCCREATE_ATTR_NAME);
            ServiceConfig peopleContConfig = structTemplateSubConfig.getSubConfig(PCCREATE_ATTR_NAME);
            ServiceConfig orgAdminConfig = structTemplateSubConfig.getSubConfig(ORG_ADMIN_ATTR_NAME);
            ServiceConfig helpDeskAdminConfig = structTemplateSubConfig.getSubConfig(HELP_DESK_ADMIN_ATTR_NAME);
            ServiceConfig policyAdminConfig = structTemplateSubConfig.getSubConfig(POLICY_ADMIN_ATTR_NAME);
            defaultGCCreateDuringOrgConfig = getConfigAttributeValue(groupContConfig, defaultGCCreateDuringOrgConfig);
            defaultPCCreateDuringOrgConfig = getConfigAttributeValue(peopleContConfig, defaultPCCreateDuringOrgConfig);
            defaultORGADMIN = getConfigAttributeValue(orgAdminConfig, defaultORGADMIN);
            defaultHELP_DESK_ADMIN = getConfigAttributeValue(helpDeskAdminConfig, defaultHELP_DESK_ADMIN);
            defaultPOLICY_ADMIN = getConfigAttributeValue(policyAdminConfig, defaultPOLICY_ADMIN);
            ServiceSchemaManager sm = new ServiceSchemaManager(CONSOLE_SERVICE_NAME, mgr.createSSOToken(new AuthPrincipal(adminDN), adminPassword));
            if (!addedListener) {
                addedListener = true;
                sm.addListener(new AdminInterfaceUtils());
            }
            ServiceSchema schema = sm.getGlobalSchema();
            defaultAC = getAttributeValue(schema, AC_ATTR_NAME, defaultAC);
            defaultGC = getAttributeValue(schema, GC_ATTR_NAME, defaultGC);
            defaultPC = getAttributeValue(schema, PC_ATTR_NAME, defaultPC);
        } catch (Exception e) {
            // Use the default values, and write out debug warning msg
            debug.warning("AdminInterfaceUtils: Unable to get " + "default People, Groups, Org Admin Role, " + "Help Desk Admin Role, Policy Admin Role and " + "Agents containers from SM", e);
        }
        if (debug.messageEnabled()) {
            debug.message("AdminInterfaceUtils: Defaults container: " + defaultPC + ", " + defaultGC + ", " + defaultAC + ", " + defaultPCCreateDuringOrgConfig + ", " + defaultGCCreateDuringOrgConfig + ", " + defaultORGADMIN + ", " + defaultHELP_DESK_ADMIN + ", " + defaultPOLICY_ADMIN);
        }
        initialized = true;
    }
}
Also used : SSOTokenManager(com.iplanet.sso.SSOTokenManager) ServiceSchema(com.sun.identity.sm.ServiceSchema) AdminDNAction(com.sun.identity.security.AdminDNAction) AdminPasswordAction(com.sun.identity.security.AdminPasswordAction) ServiceConfig(com.sun.identity.sm.ServiceConfig) AuthPrincipal(com.sun.identity.authentication.internal.AuthPrincipal) ServiceConfigManager(com.sun.identity.sm.ServiceConfigManager) ServiceSchemaManager(com.sun.identity.sm.ServiceSchemaManager) SMSException(com.sun.identity.sm.SMSException) AMException(com.iplanet.am.sdk.AMException) SSOException(com.iplanet.sso.SSOException)

Example 35 with SSOTokenManager

use of com.iplanet.sso.SSOTokenManager in project OpenAM by OpenRock.

the class TokenGenerationService method validateAssertionSubjectSession.

private SSOToken validateAssertionSubjectSession(TokenGenerationServiceInvocationState invocationState) throws ForbiddenException {
    SSOToken subjectToken;
    SSOTokenManager tokenManager;
    try {
        tokenManager = SSOTokenManager.getInstance();
        subjectToken = tokenManager.createSSOToken(invocationState.getSsoTokenString());
    } catch (SSOException e) {
        logger.debug("Exception caught creating the SSO token from the token string, almost certainly " + "because token string does not correspond to a valid session: " + e);
        throw new ForbiddenException(e.toString(), e);
    }
    if (!tokenManager.isValidToken(subjectToken)) {
        throw new ForbiddenException("SSO token string does not correspond to a valid SSOToken");
    }
    try {
        AMIdentity subjectIdentity = IdUtils.getIdentity(subjectToken);
        String invocationRealm = invocationState.getRealm();
        String subjectSessionRealm = DNMapper.orgNameToRealmName(subjectIdentity.getRealm());
        logger.debug("TokenGenerationService:validateAssertionSubjectSession subjectRealm " + subjectSessionRealm + " invocation realm: " + invocationRealm);
        if (!invocationRealm.equalsIgnoreCase(subjectSessionRealm)) {
            logger.error("TokenGenerationService:validateAssertionSubjectSession realms do not match: Subject realm : " + subjectSessionRealm + " invocation realm: " + invocationRealm);
            throw new ForbiddenException("SSO token subject realm does not match invocation realm");
        }
    } catch (SSOException | IdRepoException e) {
        logger.error("TokenGenerationService:validateAssertionSubjectSession error while validating identity : " + e);
        throw new ForbiddenException(e.toString(), e);
    }
    return subjectToken;
}
Also used : SSOTokenManager(com.iplanet.sso.SSOTokenManager) ForbiddenException(org.forgerock.json.resource.ForbiddenException) SSOToken(com.iplanet.sso.SSOToken) AMIdentity(com.sun.identity.idm.AMIdentity) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException)

Aggregations

SSOTokenManager (com.iplanet.sso.SSOTokenManager)53 SSOToken (com.iplanet.sso.SSOToken)48 SSOException (com.iplanet.sso.SSOException)39 IdRepoException (com.sun.identity.idm.IdRepoException)11 AMIdentity (com.sun.identity.idm.AMIdentity)9 AuthLoginException (com.sun.identity.authentication.spi.AuthLoginException)8 IOException (java.io.IOException)7 Map (java.util.Map)6 Set (java.util.Set)6 ForbiddenException (org.forgerock.json.resource.ForbiddenException)6 SessionException (com.iplanet.dpro.session.SessionException)5 InternalSession (com.iplanet.dpro.session.service.InternalSession)5 AuthPrincipal (com.sun.identity.authentication.internal.AuthPrincipal)5 AuthException (com.sun.identity.authentication.service.AuthException)5 Iterator (java.util.Iterator)5 AuthContext (com.sun.identity.authentication.AuthContext)4 SMSException (com.sun.identity.sm.SMSException)4 Response (com.iplanet.services.comm.share.Response)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 HashMap (java.util.HashMap)3