Search in sources :

Example 41 with SessionException

use of com.iplanet.dpro.session.SessionException in project OpenAM by OpenRock.

the class SessionService method doGetRestrictedTokenId.

/**
     * This method is expected to only be called for local sessions
     */
String doGetRestrictedTokenId(SessionID masterSid, TokenRestriction restriction) throws SessionException {
    if (statelessSessionFactory.containsJwt(masterSid)) {
        // Stateless sessions do not (yet) support restricted tokens
        throw new UnsupportedOperationException(StatelessSession.RESTRICTED_TOKENS_UNSUPPORTED);
    }
    // locate master session
    InternalSession session = cache.getBySessionID(masterSid);
    if (session == null) {
        session = recoverSession(masterSid);
        if (session == null) {
            throw new SessionException(SessionBundle.getString("invalidSessionID") + masterSid);
        }
    }
    sessionInfoFactory.validateSession(session, masterSid);
    // attempt to reuse the token if restriction is the same
    SessionID restrictedSid = session.getRestrictedTokenForRestriction(restriction);
    if (restrictedSid == null) {
        restrictedSid = session.getID().generateRelatedSessionID(serverConfig);
        SessionID previousValue = session.addRestrictedToken(restrictedSid, restriction);
        if (previousValue == null) {
            cache.put(session);
        } else {
            restrictedSid = previousValue;
        }
    }
    return restrictedSid.toString();
}
Also used : SessionException(com.iplanet.dpro.session.SessionException) SessionID(com.iplanet.dpro.session.SessionID)

Example 42 with SessionException

use of com.iplanet.dpro.session.SessionException in project OpenAM by OpenRock.

the class MultiServerClusterMonitor method locateCurrentHostServer.

/**
     * Determines current hosting server instance for internal request routing
     * mode.
     *
     * @param sid session id
     * @return server id for the server instance determined to be the current
     *         host
     * @throws com.iplanet.dpro.session.SessionException
     */
String locateCurrentHostServer(SessionID sid) throws SessionException {
    String primaryID = sid.getExtension().getPrimaryID();
    String serverID = sid.getSessionServerID();
    // if this is our local Server
    if (serverConfig.isLocalServer(serverID)) {
        return serverID;
    }
    // if session is from remote site
    if (!serverConfig.isPrimaryServer(serverID)) {
        return serverID;
    }
    // Ensure we have a Cluster State Service Available.
    synchronized (this) {
        if (clusterStateService == null) {
            try {
                initializeClusterService();
            } catch (Exception e) {
                sessionDebug.error("Unable to Initialize the Cluster Service, please review Configuration settings.", e);
                throw new SessionException(e);
            }
        }
    }
    // Check for Service Available.
    if (clusterStateService.isUp(primaryID)) {
        return primaryID;
    } else {
        int selectionListSize = clusterStateService.getServerSelectionListSize();
        String sKey = sid.getExtension().getStorageKey();
        if (sKey == null) {
            throw new SessionException("SessionService.locateCurrentHostServer: StorageKey is null");
        }
        PermutationGenerator perm = new PermutationGenerator(sKey.hashCode(), selectionListSize);
        String selectedServerId = null;
        for (int i = 0; i < selectionListSize; ++i) {
            selectedServerId = clusterStateService.getServerSelection(perm.itemAt(i));
            if (selectedServerId == null) {
                continue;
            }
            if (clusterStateService.isUp(selectedServerId)) {
                break;
            }
        }
        // selection process is guaranteed to succeed
        return selectedServerId;
    }
}
Also used : SessionException(com.iplanet.dpro.session.SessionException) PermutationGenerator(com.iplanet.dpro.session.service.PermutationGenerator) SessionException(com.iplanet.dpro.session.SessionException)

Example 43 with SessionException

use of com.iplanet.dpro.session.SessionException in project OpenAM by OpenRock.

the class LoginState method setSessionProperties.

/**
     * Populates session with properties.
     *
     * @param session
     * @throws AuthException
     */
public void setSessionProperties(InternalSession session) throws AuthException {
    if (DEBUG.messageEnabled()) {
        DEBUG.message("LoginState getSession = " + session + " \nrequest token = " + token);
    }
    if (token == null) {
        throw new AuthException(AMAuthErrorCode.AUTH_ERROR, null);
    }
    String cookieSupport = (cookieSupported) ? "true" : "false";
    // for user based DN is already set
    if (userDN == null) {
        userDN = getUserDN(amIdentityUser);
    }
    AMIdentity newAMIdentity = null;
    String oldUserDN = null;
    String oldAuthenticationModuleInstanceName = null;
    AMIdentity oldAMIdentity = null;
    if (oldSession != null || oldStatelessSession != null) {
        if (oldSession != null) {
            oldUserDN = oldSession.getProperty(ISAuthConstants.PRINCIPAL);
            oldAuthenticationModuleInstanceName = oldSession.getProperty(ISAuthConstants.AUTH_TYPE);
        } else {
            try {
                oldUserDN = oldStatelessSession.getProperty(ISAuthConstants.PRINCIPAL);
                oldAuthenticationModuleInstanceName = oldStatelessSession.getProperty(ISAuthConstants.AUTH_TYPE);
            } catch (SessionException e) {
                throw new AuthException(AMAuthErrorCode.SESSION_UPGRADE_FAILED, null);
            }
        }
        if (!ignoreUserProfile) {
            newAMIdentity = LazyConfig.AUTHD.getIdentity(IdType.USER, userDN, getOrgDN());
            oldAMIdentity = LazyConfig.AUTHD.getIdentity(IdType.USER, oldUserDN, getOrgDN());
            if (DEBUG.messageEnabled()) {
                DEBUG.message("LoginState.setSessionProperties()" + " newAMIdentity is: " + newAMIdentity);
                DEBUG.message("LoginState.setSessionProperties()" + " oldAMIdentity is: " + oldAMIdentity);
            }
        }
    }
    if (DEBUG.messageEnabled()) {
        DEBUG.message("LoginState.setSessionProperties()" + " userDN is: " + userDN);
        DEBUG.message("LoginState.setSessionProperties()" + " oldUserDN is: " + oldUserDN);
        DEBUG.message("LoginState.setSessionProperties()" + " sessionUpgrade is: " + sessionUpgrade);
    }
    if (sessionUpgrade) {
        String oldAuthenticationModuleClassName = null;
        if ((oldAuthenticationModuleInstanceName != null) && (!oldAuthenticationModuleInstanceName.contains("|"))) {
            try {
                SSOToken adminToken = AccessController.doPrivileged(AdminTokenAction.getInstance());
                AMAuthenticationManager authManager = new AMAuthenticationManager(adminToken, getOrgName());
                AMAuthenticationInstance authInstance = authManager.getAuthenticationInstance(oldAuthenticationModuleInstanceName);
                oldAuthenticationModuleClassName = authInstance.getType();
            } catch (AMConfigurationException ace) {
                if (DEBUG.messageEnabled()) {
                    DEBUG.message("LoginState.setSessionProperties()" + ":Unable to create AMAuthenticationManager" + "Instance:" + ace.getMessage());
                }
                throw new AuthException(ace);
            }
        }
        if ("Anonymous".equalsIgnoreCase(oldAuthenticationModuleClassName)) {
            sessionUpgrade();
        } else if (!ignoreUserProfile) {
            if ((oldAMIdentity != null) && oldAMIdentity.equals(newAMIdentity)) {
                sessionUpgrade();
            } else {
                if (DEBUG.messageEnabled()) {
                    DEBUG.message("LoginState.setSessionProperties()" + "Resetting session upgrade to false " + "since oldAMIdentity and newAMIdentity doesn't match");
                }
                throw new AuthException(AMAuthErrorCode.SESSION_UPGRADE_FAILED, null);
            }
        } else {
            if ((oldUserDN != null) && (DNUtils.normalizeDN(userDN)).equals(DNUtils.normalizeDN(oldUserDN))) {
                sessionUpgrade();
            } else {
                if (DEBUG.messageEnabled()) {
                    DEBUG.message("LoginState.setSessionProperties()" + "Resetting session upgrade to false " + "since Old UserDN and New UserDN doesn't match");
                }
                throw new AuthException(AMAuthErrorCode.SESSION_UPGRADE_FAILED, null);
            }
        }
    }
    if (forceAuth && sessionUpgrade) {
        session = oldSession;
    }
    Date authInstantDate = new Date();
    String authInstant = DateUtils.toUTCDateFormat(authInstantDate);
    String moduleAuthTime = null;
    if (sessionUpgrade) {
        try {
            if (oldStatelessSession != null) {
                oldSSOToken = SSOTokenManager.getInstance().createSSOToken(oldStatelessSession.getID().toString());
            } else {
                oldSSOToken = SSOTokenManager.getInstance().createSSOToken(oldSession.getID().toString());
            }
        } catch (SSOException ssoExp) {
            DEBUG.error("LoginState.setSessionProperties: Cannot get " + "oldSSOToken.");
        }
        Map<String, String> moduleTimeMap = null;
        if (oldSSOToken != null) {
            moduleTimeMap = AMAuthUtils.getModuleAuthTimeMap(oldSSOToken);
        }
        if (moduleTimeMap == null) {
            moduleTimeMap = new HashMap<String, String>();
        }
        StringTokenizer tokenizer = new StringTokenizer(authMethName, ISAuthConstants.PIPE_SEPARATOR);
        while (tokenizer.hasMoreTokens()) {
            String moduleName = tokenizer.nextToken();
            moduleTimeMap.put(moduleName, authInstant);
        }
        boolean firstElement = true;
        for (Map.Entry<String, String> entry : moduleTimeMap.entrySet()) {
            String moduleName = entry.getKey();
            String authTime = entry.getValue();
            StringBuilder sb = new StringBuilder();
            if (!firstElement) {
                sb.append(ISAuthConstants.PIPE_SEPARATOR);
            }
            firstElement = false;
            if (moduleAuthTime == null) {
                moduleAuthTime = (sb.append(moduleName).append("+").append(authTime)).toString();
            } else {
                moduleAuthTime += sb.append(moduleName).append("+").append(authTime);
            }
        }
    }
    //Sets the User profile option used, in session.
    String userProfile = ISAuthConstants.REQUIRED;
    if (dynamicProfileCreation) {
        userProfile = ISAuthConstants.CREATE;
    } else if (ignoreUserProfile) {
        userProfile = ISAuthConstants.IGNORE;
    } else if (createWithAlias) {
        userProfile = ISAuthConstants.CREATE_WITH_ALIAS;
    }
    session.putProperty(ISAuthConstants.USER_PROFILE, userProfile);
    String defaultLoginURL = null;
    if (loginURL != null) {
        int questionMark = loginURL.indexOf("?");
        defaultLoginURL = loginURL;
        if (questionMark != -1) {
            defaultLoginURL = loginURL.substring(0, questionMark);
        }
        session.putProperty(ISAuthConstants.LOGIN_URL, defaultLoginURL);
        session.putProperty(ISAuthConstants.FULL_LOGIN_URL, loginURL);
    }
    String sessionSuccessURL = LazyConfig.AUTHD.processURL(successLoginURL, servletRequest);
    sessionSuccessURL = encodeURL(sessionSuccessURL, servletResponse, true);
    if (sessionSuccessURL != null) {
        session.putProperty(ISAuthConstants.SUCCESS_URL, sessionSuccessURL);
    }
    // Get the universal ID
    String univId = null;
    if (amIdentityUser != null) {
        univId = IdUtils.getUniversalId(amIdentityUser);
    }
    String userId = DNUtils.DNtoName(userDN);
    if (DEBUG.messageEnabled()) {
        DEBUG.message("setSessionProperties Principal = " + userDN + "\n" + "UserId = " + token + "\n" + "client = " + getClient() + "\n" + "Organization = " + orgDN + "\n" + "locale = " + localeContext.getLocale() + "\n" + "charset = " + localeContext.getMIMECharset() + "\n" + "idleTime = " + idleTime + "\n" + "cacheTime = " + cacheTime + "\n" + "maxSession = " + maxSession + "\n" + "AuthLevel = " + authLevel + "\n" + "AuthType = " + authMethName + "\n" + "Subject = " + subject.toString() + "\n" + "UniversalId = " + univId + "\n" + "cookieSupport = " + cookieSupport + "\n" + "principals = " + principalList + "\n" + "defaultLoginURL = " + defaultLoginURL + "\n" + "successURL = " + sessionSuccessURL + "\n" + "IndexType = " + indexType + "\n" + "UserProfile = " + userProfile + "\n" + "AuthInstant = " + authInstant + "\n" + "ModuleAuthTime = " + moduleAuthTime);
    }
    try {
        if ((isApplicationModule(authMethName) && (LazyConfig.AUTHD.isSuperUser(userDN) || LazyConfig.AUTHD.isSpecialUser(userDN))) || isAgent(amIdentityUser)) {
            session.setClientID(token);
            session.setType(APPLICATION_SESSION);
            if (isAgent(amIdentityUser) && AGENT_SESSION_IDLE_TIME > 0) {
                if (DEBUG.messageEnabled()) {
                    DEBUG.message("setSessionProperties for agent " + userDN + " with idletimeout to " + AGENT_SESSION_IDLE_TIME);
                }
                session.setMaxSessionTime(Long.MAX_VALUE / 60);
                session.setMaxIdleTime(AGENT_SESSION_IDLE_TIME);
                session.setMaxCachingTime(AGENT_SESSION_IDLE_TIME);
            } else {
                if (DEBUG.messageEnabled()) {
                    DEBUG.message("setSessionProperties for non-expiring session");
                }
                session.setExpire(false);
            }
        } else {
            DEBUG.message("request: in putProperty stuff");
            session.setClientID(userDN);
            session.setType(USER_SESSION);
            session.setMaxSessionTime(maxSession);
            session.setMaxIdleTime(idleTime);
            session.setMaxCachingTime(cacheTime);
        }
        session.setClientDomain(getOrgDN());
        if ((client = getClient()) != null) {
            session.putProperty(ISAuthConstants.HOST, client);
        }
        if (!sessionUpgrade) {
            session.putProperty(ISAuthConstants.AUTH_LEVEL, Integer.toString(authLevel));
            session.putProperty(ISAuthConstants.AUTH_TYPE, authMethName);
        }
        session.putProperty(ISAuthConstants.PRINCIPAL, userDN);
        if (userId == null && userDN != null) {
            DN dnObj = DN.valueOf(userDN);
            if (dnObj.size() > 0) {
                userId = LDAPUtils.rdnValueFromDn(dnObj);
            }
        }
        session.putProperty(ISAuthConstants.USER_ID, userId);
        session.putProperty(ISAuthConstants.USER_TOKEN, token);
        session.putProperty(ISAuthConstants.ORGANIZATION, getOrgDN());
        session.putProperty(ISAuthConstants.LOCALE, localeContext.getLocale().toString());
        session.putProperty(ISAuthConstants.CHARSET, localeContext.getMIMECharset());
        session.putProperty(ISAuthConstants.CLIENT_TYPE, getClientType());
        session.putProperty(ISAuthConstants.COOKIE_SUPPORT_PROPERTY, cookieSupport);
        session.putProperty(ISAuthConstants.AUTH_INSTANT, authInstant);
        if ((moduleAuthTime != null) && (moduleAuthTime.length() != 0)) {
            session.putProperty(ISAuthConstants.MODULE_AUTH_TIME, moduleAuthTime);
        }
        if (principalList != null) {
            session.putProperty(ISAuthConstants.PRINCIPALS, principalList);
        }
        if (indexType != null) {
            session.putProperty(ISAuthConstants.INDEX_TYPE, indexType.toString());
        }
        if (univId != null) {
            session.putProperty(Constants.UNIVERSAL_IDENTIFIER, univId);
        } else if (userDN != null) {
            session.putProperty(Constants.UNIVERSAL_IDENTIFIER, userDN);
        }
        if ((indexType == AuthContext.IndexType.ROLE) && (indexName != null)) {
            if (!sessionUpgrade) {
                session.putProperty(ISAuthConstants.ROLE, indexName);
            }
        }
        if (!sessionUpgrade) {
            String finalAuthConfig = getAuthConfigName(indexType, indexName);
            if ((finalAuthConfig != null) && (finalAuthConfig.length() != 0)) {
                session.putProperty(ISAuthConstants.SERVICE, finalAuthConfig);
            }
        }
        if ((userSessionMapping != null) && !(userSessionMapping.isEmpty()) && !ignoreUserProfile) {
            for (final String mapping : userSessionMapping) {
                if ((mapping != null) && (mapping.length() != 0)) {
                    StringTokenizer tokenizer = new StringTokenizer(mapping, "|");
                    String userAttribute = null;
                    String sessionAttribute = null;
                    if (tokenizer.hasMoreTokens()) {
                        userAttribute = tokenizer.nextToken();
                    }
                    if (tokenizer.hasMoreTokens()) {
                        sessionAttribute = tokenizer.nextToken();
                    }
                    if ((userAttribute != null) && (userAttribute.length() != 0)) {
                        Set userAttrValueSet = amIdentityUser.getAttribute(userAttribute);
                        if ((userAttrValueSet != null) && !(userAttrValueSet.isEmpty())) {
                            Iterator valueIter = userAttrValueSet.iterator();
                            StringBuilder strBuffValues = new StringBuilder();
                            while (valueIter.hasNext()) {
                                String userAttrValue = (String) valueIter.next();
                                if (strBuffValues.length() == 0) {
                                    strBuffValues.append(userAttrValue);
                                } else {
                                    strBuffValues.append("|").append(userAttrValue);
                                }
                            }
                            if (sessionAttribute != null) {
                                session.putProperty(Constants.AM_PROTECTED_PROPERTY_PREFIX + "." + sessionAttribute, strBuffValues.toString());
                            } else {
                                session.putProperty(Constants.AM_PROTECTED_PROPERTY_PREFIX + "." + userAttribute, strBuffValues.toString());
                            }
                        }
                    }
                }
            }
        }
        // Set Attribute Map for Authentication module
        AuthenticationPrincipalDataRetriever principalDataRetriever = AuthenticationPrincipalDataRetrieverFactory.getPrincipalDataRetriever();
        if (principalDataRetriever != null) {
            Map<String, String> attrMap = principalDataRetriever.getAttrMapForAuthenticationModule(subject);
            if (attrMap != null && !attrMap.isEmpty()) {
                for (Map.Entry<String, String> entry : attrMap.entrySet()) {
                    String attrName = entry.getKey();
                    String attrValue = entry.getValue();
                    session.putProperty(attrName, attrValue);
                    if (DEBUG.messageEnabled()) {
                        DEBUG.message("AttrMap for SAML : " + attrName + " , " + attrValue);
                    }
                }
            }
        }
    } catch (Exception e) {
        DEBUG.error("Exception in setSession ", e);
        throw new AuthException(e);
    }
}
Also used : SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) SessionException(com.iplanet.dpro.session.SessionException) SSOException(com.iplanet.sso.SSOException) DN(org.forgerock.opendj.ldap.DN) Date(java.util.Date) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SSOException(com.iplanet.sso.SSOException) AMConfigurationException(com.sun.identity.authentication.config.AMConfigurationException) IdRepoException(com.sun.identity.idm.IdRepoException) AuthenticationException(com.sun.identity.authentication.spi.AuthenticationException) AMException(com.iplanet.am.sdk.AMException) SessionException(com.iplanet.dpro.session.SessionException) StringTokenizer(java.util.StringTokenizer) AMIdentity(com.sun.identity.idm.AMIdentity) Iterator(java.util.Iterator) AMConfigurationException(com.sun.identity.authentication.config.AMConfigurationException) AMAuthenticationInstance(com.sun.identity.authentication.config.AMAuthenticationInstance) Map(java.util.Map) HashMap(java.util.HashMap) AMAuthenticationManager(com.sun.identity.authentication.config.AMAuthenticationManager)

Example 44 with SessionException

use of com.iplanet.dpro.session.SessionException in project OpenAM by OpenRock.

the class DefaultSessionActivator method updateSessions.

/**
     * newSession and sessionToActivate may be the same session -- e.g. in the default case for normal or stateless
     * tokens. In other circumstances they will differ (i.e. ForceAuth).
     */
protected boolean updateSessions(InternalSession newSession, LoginState loginState, InternalSession sessionToActivate, InternalSession authSession, SessionService sessionService, Subject subject, Object loginContext) throws AuthException {
    final SessionID authSessionId = authSession.getID();
    newSession.removeObject(ISAuthConstants.AUTH_CONTEXT_OBJ);
    //session upgrade and anonymous conditions are handled in here
    loginState.setSessionProperties(newSession);
    //copy in our auth session properties (if any)
    putAllPropertiesFromAuthSession(authSession, sessionToActivate);
    //destroying the authentication session
    sessionService.destroyInternalSession(authSessionId);
    if (DEBUG.messageEnabled()) {
        DEBUG.message("Activating session: " + newSession);
    }
    //ensure that we've updated the subject (if appropriate, e.g. from anonymous -> known)
    loginState.setSubject(addSSOTokenPrincipal(subject, sessionToActivate.getID()));
    //set the login context for this session
    if (loginState.isModulesInSessionEnabled() && loginContext != null) {
        newSession.setObject(ISAuthConstants.LOGIN_CONTEXT, loginContext);
    }
    try {
        return activateSession(sessionToActivate, loginState);
    } catch (SessionException e) {
        throw new AuthException(e);
    }
}
Also used : SessionException(com.iplanet.dpro.session.SessionException) SessionID(com.iplanet.dpro.session.SessionID)

Example 45 with SessionException

use of com.iplanet.dpro.session.SessionException in project OpenAM by OpenRock.

the class ResourceResultCache method getPolicyServiceURL.

/**
    * Returns policy service URL based on session token
    * @param token session token of user
    * @return policy service URL based on session token
    * @throws PolicyException if can not get policy service URL
    */
static URL getPolicyServiceURL(SSOToken token) throws PolicyException {
    URL policyServiceURL = null;
    try {
        String ssoTokenID = token.getTokenID().toString();
        SessionID sid = new SessionID(ssoTokenID);
        Session session = sessionCache.getSession(sid);
        URL sessionServiceURL = session.getSessionServiceURL();
        String protocol = sessionServiceURL.getProtocol();
        String host = sessionServiceURL.getHost();
        int port = sessionServiceURL.getPort();
        String uri = sessionServiceURL.getPath();
        String portString = null;
        if (port == -1) {
            portString = "";
        } else {
            portString = Integer.toString(port);
        }
        policyServiceURL = WebtopNaming.getServiceURL(POLICY_SERVICE_ID_FOR_NAMING, protocol, host, portString, uri);
    } catch (SessionException se) {
        debug.error("ResourceResultCache.getPolicyServiceURL():" + "Can not find policy service URL", se);
        throw new PolicyEvaluationException(ResBundleUtils.rbName, "policy_service_url_not_found", null, se);
    } catch (URLNotFoundException ue) {
        debug.error("ResourceResultCache.getPolicyServiceURL():" + "Can not find policy service URL", ue);
        throw new PolicyEvaluationException(ResBundleUtils.rbName, "policy_service_url_not_found", null, ue);
    }
    return policyServiceURL;
}
Also used : SessionException(com.iplanet.dpro.session.SessionException) PolicyEvaluationException(com.sun.identity.policy.remote.PolicyEvaluationException) URLNotFoundException(com.iplanet.services.naming.URLNotFoundException) SessionID(com.iplanet.dpro.session.SessionID) URL(java.net.URL) Session(com.iplanet.dpro.session.Session)

Aggregations

SessionException (com.iplanet.dpro.session.SessionException)60 SessionID (com.iplanet.dpro.session.SessionID)22 Session (com.iplanet.dpro.session.Session)18 SSOException (com.iplanet.sso.SSOException)15 SessionResponse (com.iplanet.dpro.session.share.SessionResponse)9 SessionInfo (com.iplanet.dpro.session.share.SessionInfo)8 URL (java.net.URL)8 Map (java.util.Map)7 Test (org.testng.annotations.Test)7 InternalSession (com.iplanet.dpro.session.service.InternalSession)6 SessionRequest (com.iplanet.dpro.session.share.SessionRequest)6 IdRepoException (com.sun.identity.idm.IdRepoException)6 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)6 DelegationException (com.sun.identity.delegation.DelegationException)5 InterruptedIOException (java.io.InterruptedIOException)5 ConnectException (java.net.ConnectException)5 HashSet (java.util.HashSet)5 Set (java.util.Set)5 TokenRestriction (com.iplanet.dpro.session.TokenRestriction)4 SSOToken (com.iplanet.sso.SSOToken)4