Search in sources :

Example 6 with SessionContext

use of org.wso2.carbon.identity.application.authentication.framework.context.SessionContext in project carbon-identity-framework by wso2.

the class DefaultLogoutRequestHandler method handle.

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws FrameworkException {
    if (log.isTraceEnabled()) {
        log.trace("Inside handle()");
    }
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    // Retrieve session information from cache.
    SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(context.getSessionIdentifier(), context.getLoginTenantDomain());
    ExternalIdPConfig externalIdPConfig = null;
    // Remove the session related information from the session tables.
    clearUserSessionData(request);
    if (FrameworkServiceDataHolder.getInstance().getAuthnDataPublisherProxy() != null && FrameworkServiceDataHolder.getInstance().getAuthnDataPublisherProxy().isEnabled(context) && sessionContext != null) {
        Object authenticatedUserObj = sessionContext.getProperty(FrameworkConstants.AUTHENTICATED_USER);
        AuthenticatedUser authenticatedUser = new AuthenticatedUser();
        if (authenticatedUserObj instanceof AuthenticatedUser) {
            authenticatedUser = (AuthenticatedUser) authenticatedUserObj;
        }
        FrameworkUtils.publishSessionEvent(context.getSessionIdentifier(), request, context, sessionContext, authenticatedUser, FrameworkConstants.AnalyticsAttributes.SESSION_TERMINATE);
    }
    // Remove federated authentication session details from the database.
    if (sessionContext != null && StringUtils.isNotBlank(context.getSessionIdentifier()) && sessionContext.getSessionAuthHistory() != null && sessionContext.getSessionAuthHistory().getHistory() != null) {
        for (AuthHistory authHistory : sessionContext.getSessionAuthHistory().getHistory()) {
            if (FED_AUTH_NAME.equals(authHistory.getAuthenticatorName())) {
                try {
                    UserSessionStore.getInstance().removeFederatedAuthSessionInfo(context.getSessionIdentifier());
                    break;
                } catch (UserSessionException e) {
                    throw new FrameworkException("Error while deleting federated authentication session details for" + " the session context key :" + context.getSessionIdentifier(), e);
                }
            }
        }
    }
    // remove SessionContext from the cache and auth cookie before sending logout request to federated IDP,
    // without waiting till a logout response is received from federated IDP.
    // remove the SessionContext from the cache
    FrameworkUtils.removeSessionContextFromCache(context.getSessionIdentifier(), context.getLoginTenantDomain());
    // remove the cookie
    if (IdentityTenantUtil.isTenantedSessionsEnabled()) {
        FrameworkUtils.removeAuthCookie(request, response, context.getLoginTenantDomain());
    } else {
        FrameworkUtils.removeAuthCookie(request, response);
    }
    if (context.isPreviousSessionFound()) {
        // if this is the start of the logout sequence
        if (context.getCurrentStep() == 0) {
            context.setCurrentStep(1);
        }
        int stepCount = sequenceConfig.getStepMap().size();
        while (context.getCurrentStep() <= stepCount) {
            int currentStep = context.getCurrentStep();
            StepConfig stepConfig = sequenceConfig.getStepMap().get(currentStep);
            AuthenticatorConfig authenticatorConfig = stepConfig.getAuthenticatedAutenticator();
            if (authenticatorConfig == null) {
                authenticatorConfig = sequenceConfig.getAuthenticatedReqPathAuthenticator();
            }
            ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator();
            String idpName = stepConfig.getAuthenticatedIdP();
            // TODO: Need to fix occurrences where idPName becomes "null"
            if ((idpName == null || "null".equalsIgnoreCase(idpName) || idpName.isEmpty()) && sequenceConfig.getAuthenticatedReqPathAuthenticator() != null) {
                idpName = FrameworkConstants.LOCAL_IDP_NAME;
            }
            try {
                externalIdPConfig = ConfigurationFacade.getInstance().getIdPConfigByName(idpName, context.getTenantDomain());
                context.setExternalIdP(externalIdPConfig);
                context.setAuthenticatorProperties(FrameworkUtils.getAuthenticatorPropertyMapFromIdP(externalIdPConfig, authenticator.getName()));
                if (authenticatorConfig.getAuthenticatorStateInfo() != null) {
                    context.setStateInfo(authenticatorConfig.getAuthenticatorStateInfo());
                } else {
                    context.setStateInfo(getStateInfoFromPreviousAuthenticatedIdPs(idpName, authenticatorConfig.getName(), context));
                }
                AuthenticatorFlowStatus status = authenticator.process(request, response, context);
                request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, status);
                if (!status.equals(AuthenticatorFlowStatus.INCOMPLETE)) {
                    // TODO what if logout fails. this is an edge case
                    currentStep++;
                    context.setCurrentStep(currentStep);
                    continue;
                }
                // sends the logout request to the external IdP
                return;
            } catch (AuthenticationFailedException | LogoutFailedException e) {
                throw new FrameworkException("Exception while handling logout request", e);
            } catch (IdentityProviderManagementException e) {
                log.error("Exception while getting IdP by name", e);
            }
        }
    }
    try {
        sendResponse(request, response, context, true);
    } catch (ServletException | IOException e) {
        throw new FrameworkException(e.getMessage(), e);
    }
}
Also used : AuthenticatorConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) LogoutFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException) IOException(java.io.IOException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) UserSessionException(org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException) ServletException(javax.servlet.ServletException) ApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator) SessionContext(org.wso2.carbon.identity.application.authentication.framework.context.SessionContext) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) ExternalIdPConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ExternalIdPConfig) AuthHistory(org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory) AuthenticatorFlowStatus(org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Example 7 with SessionContext

use of org.wso2.carbon.identity.application.authentication.framework.context.SessionContext in project identity-data-publisher-authentication by wso2-extensions.

the class AuthnDataPublisherProxy method publishSessionTermination.

/**
 * Publishes session termination
 *
 * @param request         Incoming request for authentication
 * @param context         Authentication context
 * @param sessionContext  Session context
 * @param unmodifiableMap Other relevant parameters which needs to be published
 */
public void publishSessionTermination(HttpServletRequest request, AuthenticationContext context, SessionContext sessionContext, Map<String, Object> unmodifiableMap) {
    Event event = createEvent(request, context, sessionContext, unmodifiableMap, EventName.SESSION_TERMINATE);
    doPublishEvent(event);
    for (AuthenticationDataPublisher publisher : dataPublishers) {
        if (isPublisherEnabledAndCanHandle(context, publisher)) {
            publisher.publishSessionTermination(request, context, sessionContext, unmodifiableMap);
            if (log.isDebugEnabled()) {
                log.debug(publisher.getName() + " is invoked.");
            }
        }
    }
}
Also used : Event(org.wso2.carbon.identity.event.event.Event) AuthenticationDataPublisher(org.wso2.carbon.identity.application.authentication.framework.AuthenticationDataPublisher)

Example 8 with SessionContext

use of org.wso2.carbon.identity.application.authentication.framework.context.SessionContext in project identity-data-publisher-authentication by wso2-extensions.

the class AuthnDataPublisherProxy method createEvent.

private Event createEvent(HttpServletRequest request, AuthenticationContext context, SessionContext sessionContext, Map<String, Object> params, EventName eventName) {
    Map<String, Object> eventProperties = new HashMap<>();
    eventProperties.put(EventProperty.REQUEST, request);
    eventProperties.put(EventProperty.CONTEXT, context);
    if (sessionContext != null) {
        eventProperties.put(EventProperty.SESSION_CONTEXT, sessionContext);
    }
    eventProperties.put(EventProperty.PARAMS, params);
    Event event = new Event(eventName.name(), eventProperties);
    return event;
}
Also used : HashMap(java.util.HashMap) Event(org.wso2.carbon.identity.event.event.Event)

Example 9 with SessionContext

use of org.wso2.carbon.identity.application.authentication.framework.context.SessionContext in project identity-data-publisher-authentication by wso2-extensions.

the class AuthnDataPublisherProxy method publishSessionUpdate.

/**
 * Publishes session update after managing handler operations
 *
 * @param request         Incoming request for authentication
 * @param context         Authentication context
 * @param sessionContext  Session context
 * @param unmodifiableMap Other relevant parameters which needs to be published
 */
public void publishSessionUpdate(HttpServletRequest request, AuthenticationContext context, SessionContext sessionContext, Map<String, Object> unmodifiableMap) {
    Event event = createEvent(request, context, sessionContext, unmodifiableMap, EventName.SESSION_UPDATE);
    doPublishEvent(event);
    for (AuthenticationDataPublisher publisher : dataPublishers) {
        if (isPublisherEnabledAndCanHandle(context, publisher)) {
            publisher.publishSessionUpdate(request, context, sessionContext, unmodifiableMap);
            if (log.isDebugEnabled()) {
                log.debug(publisher.getName() + " is invoked.");
            }
        }
    }
}
Also used : Event(org.wso2.carbon.identity.event.event.Event) AuthenticationDataPublisher(org.wso2.carbon.identity.application.authentication.framework.AuthenticationDataPublisher)

Example 10 with SessionContext

use of org.wso2.carbon.identity.application.authentication.framework.context.SessionContext in project identity-data-publisher-authentication by wso2-extensions.

the class AbstractAuthenticationDataPublisher method publishSessionTermination.

/**
 * Publishes session termination
 *
 * @param request        Incoming request for authentication
 * @param context        Authentication context
 * @param sessionContext Session context
 * @param params         Other relevant parameters which needs to be published
 */
public void publishSessionTermination(HttpServletRequest request, AuthenticationContext context, SessionContext sessionContext, Map<String, Object> params) {
    if (log.isDebugEnabled()) {
        log.debug("Publishing session termination");
    }
    SessionData sessionData = new SessionData();
    Object userObj = params.get(FrameworkConstants.AnalyticsAttributes.USER);
    String sessionId = (String) params.get(FrameworkConstants.AnalyticsAttributes.SESSION_ID);
    String userName = null;
    String userStoreDomain = null;
    String tenantDomain = null;
    Long createdTime = null;
    Long currentTime = System.currentTimeMillis();
    if (userObj != null && userObj instanceof AuthenticatedUser) {
        AuthenticatedUser user = (AuthenticatedUser) userObj;
        userName = user.getUserName();
        userStoreDomain = user.getUserStoreDomain();
        tenantDomain = user.getTenantDomain();
    }
    if (sessionContext != null) {
        Object createdTimeObj = sessionContext.getProperty(FrameworkConstants.CREATED_TIMESTAMP);
        createdTime = (Long) createdTimeObj;
        sessionData.setIsRememberMe(sessionContext.isRememberMe());
    }
    sessionData.setUser(userName);
    sessionData.setUserStoreDomain(userStoreDomain);
    sessionData.setTenantDomain(tenantDomain);
    sessionData.setSessionId(sessionId);
    sessionData.setCreatedTimestamp(createdTime);
    sessionData.setUpdatedTimestamp(currentTime);
    sessionData.setIdentityProviders(getCommaSeparatedIDPs(sessionContext));
    sessionData.setTerminationTimestamp(currentTime);
    if (context != null) {
        sessionData.setServiceProvider(context.getServiceProviderName());
        sessionData.addParameter(AuthPublisherConstants.TENANT_ID, AuthnDataPublisherUtils.getTenantDomains(context.getTenantDomain(), sessionData.getTenantDomain()));
    } else {
        sessionData.addParameter(AuthPublisherConstants.TENANT_ID, new String[] { sessionData.getTenantDomain() });
    }
    if (request != null) {
        sessionData.setRemoteIP(IdentityUtil.getClientIpAddress(request));
    }
    if (params.containsKey(FrameworkConstants.AnalyticsAttributes.ACTIVE_SESSION_COUNT)) {
        int activeSessionCount = (int) params.get(FrameworkConstants.AnalyticsAttributes.ACTIVE_SESSION_COUNT);
        sessionData.setActiveSessionCount(activeSessionCount);
    }
    doPublishSessionTermination(sessionData);
}
Also used : SessionData(org.wso2.carbon.identity.data.publisher.application.authentication.model.SessionData) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Aggregations

SessionContext (org.wso2.carbon.identity.application.authentication.framework.context.SessionContext)25 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)14 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)7 Test (org.testng.annotations.Test)7 SessionContextCacheKey (org.wso2.carbon.identity.application.authentication.framework.cache.SessionContextCacheKey)7 HashMap (java.util.HashMap)6 BeforeTest (org.testng.annotations.BeforeTest)6 SessionContextCacheEntry (org.wso2.carbon.identity.application.authentication.framework.cache.SessionContextCacheEntry)6 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)6 Event (org.wso2.carbon.identity.event.event.Event)6 JSONObject (org.json.JSONObject)5 AuthenticationDataPublisher (org.wso2.carbon.identity.application.authentication.framework.AuthenticationDataPublisher)4 FrameworkException (org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException)4 PowerMockIdentityBaseTest (org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)4 ArrayList (java.util.ArrayList)3 Cookie (javax.servlet.http.Cookie)3 AuthHistory (org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory)3 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)3 Map (java.util.Map)2 AfterTest (org.testng.annotations.AfterTest)2