Search in sources :

Example 16 with SessionContext

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

the class OAuth2AuthzEndpoint method getAuthenticatedTimeFromCommonAuthCookie.

/**
 * Gets the last authenticated value from the commonAuthId cookie
 *
 * @param cookie CommonAuthId cookie
 * @param loginTenantDomain Login tenant domain
 * @return the last authenticated timestamp
 */
private long getAuthenticatedTimeFromCommonAuthCookie(Cookie cookie, String loginTenantDomain) {
    long authTime = 0;
    if (cookie != null) {
        String sessionContextKey = DigestUtils.sha256Hex(cookie.getValue());
        SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(sessionContextKey, loginTenantDomain);
        if (sessionContext != null) {
            if (sessionContext.getProperty(FrameworkConstants.UPDATED_TIMESTAMP) != null) {
                authTime = Long.parseLong(sessionContext.getProperty(FrameworkConstants.UPDATED_TIMESTAMP).toString());
            } else {
                authTime = Long.parseLong(sessionContext.getProperty(FrameworkConstants.CREATED_TIMESTAMP).toString());
            }
        }
    }
    return authTime;
}
Also used : SessionContext(org.wso2.carbon.identity.application.authentication.framework.context.SessionContext)

Example 17 with SessionContext

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

the class TokenBindingExpiryEventHandler method revokeAccessTokensMappedForSessions.

/**
 * This method will get the application information from session context and revoke access tokens of the
 * applications bound to that session. This method can be used when token binding information is not found in the
 * request.
 *
 * @param event Event.
 * @throws IdentityOAuth2Exception
 */
private void revokeAccessTokensMappedForSessions(Event event) throws IdentityOAuth2Exception {
    String sessionContextIdentifier = getSessionIdentifier(event);
    Map<String, Object> eventProperties = event.getEventProperties();
    if (StringUtils.isNotBlank(sessionContextIdentifier)) {
        SessionContext sessionContext = (SessionContext) eventProperties.get(IdentityEventConstants.EventProperty.SESSION_CONTEXT);
        if (sessionContext != null) {
            revokeTokensMappedToSession(sessionContextIdentifier);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Session context for session context identifier: " + sessionContextIdentifier + " is not found in the event");
            }
        }
    }
}
Also used : SessionContext(org.wso2.carbon.identity.application.authentication.framework.context.SessionContext)

Example 18 with SessionContext

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

the class SSOSessionBasedTokenBinder method isValidTokenBinding.

@Override
public boolean isValidTokenBinding(Object request, String bindingReference) {
    try {
        String sessionIdentifier = getTokenBindingValue((HttpServletRequest) request);
        if (StringUtils.isBlank(sessionIdentifier)) {
            if (log.isDebugEnabled()) {
                log.debug("CommonAuthId cookie is not found in the request.");
            }
            return false;
        }
        /* Retrieve session context information using sessionIdentifier in order to check the validity of
            commonAuthId cookie.*/
        SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(sessionIdentifier);
        if (sessionContext == null) {
            if (log.isDebugEnabled()) {
                log.debug("Session context is not found corresponding to the session identifier: " + sessionIdentifier);
            }
            return false;
        }
    } catch (OAuthSystemException e) {
        log.error("Error while getting the token binding value", e);
        return false;
    }
    return isValidTokenBinding(request, bindingReference, COMMONAUTH_COOKIE);
}
Also used : OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) SessionContext(org.wso2.carbon.identity.application.authentication.framework.context.SessionContext)

Example 19 with SessionContext

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

the class SessionDataPublisherImpl method publishSessionTermination.

/**
 * Overridden method which implements the access token revocation
 * @param request termination request
 * @param context termination context
 * @param sessionContext termination sessionContext
 * @param params termination params
 */
@Override
public void publishSessionTermination(HttpServletRequest request, AuthenticationContext context, SessionContext sessionContext, Map<String, Object> params) {
    OAuthConsumerAppDTO[] appDTOs = new OAuthConsumerAppDTO[0];
    List<OAuthConsumerAppDTO> revokeAppList = new ArrayList<>();
    AuthenticatedUser authenticatedUser = (AuthenticatedUser) params.get(user);
    String username = authenticatedUser.getUserName();
    String tenantDomain = authenticatedUser.getTenantDomain();
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    AuthenticatedUser federatedUser;
    SystemApplicationDTO[] systemApplicationDTOS = new SystemApplicationDTO[0];
    if (authenticatedUser.isFederatedUser()) {
        try {
            federatedUser = buildAuthenticatedUser(authenticatedUser);
            authenticatedUser = federatedUser;
        } catch (IdentityOAuth2Exception e) {
            log.error("Error thrown while building authenticated user in logout flow for user " + authenticatedUser.getUserName(), e);
        }
    }
    SystemApplicationDAO systemApplicationDAO = new SystemApplicationDAO();
    try {
        systemApplicationDTOS = systemApplicationDAO.getApplications(tenantDomain);
        if (systemApplicationDTOS.length < 0) {
            if (log.isDebugEnabled()) {
                log.debug("The tenant: " + tenantDomain + " doesn't have any system apps");
            }
        }
    } catch (APIMgtDAOException e) {
        log.error("Error thrown while retrieving system applications for the tenant domain " + tenantDomain, e);
    }
    try {
        appDTOs = getAppsAuthorizedByUser(authenticatedUser);
        if (appDTOs.length > 0) {
            if (log.isDebugEnabled()) {
                log.debug("The user: " + authenticatedUser.getUserName() + " has " + appDTOs.length + " OAuth apps");
            }
        }
    } catch (IdentityOAuthAdminException e) {
        log.error("Error while retrieving applications authorized for the user " + authenticatedUser.getUserName(), e);
    }
    for (OAuthConsumerAppDTO appDTO : appDTOs) {
        for (SystemApplicationDTO systemApplicationDTO : systemApplicationDTOS) {
            if (StringUtils.equalsIgnoreCase(appDTO.getOauthConsumerKey(), systemApplicationDTO.getConsumerKey())) {
                revokeAppList.add(appDTO);
            }
        }
    }
    for (OAuthConsumerAppDTO appDTO : revokeAppList) {
        Set<AccessTokenDO> accessTokenDOs = null;
        try {
            // Retrieve all ACTIVE or EXPIRED access tokens for particular client authorized by this user
            accessTokenDOs = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getAccessTokens(appDTO.getOauthConsumerKey(), authenticatedUser, authenticatedUser.getUserStoreDomain(), true);
        } catch (IdentityOAuth2Exception e) {
            log.error("Error while retrieving access tokens for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
        }
        AuthenticatedUser authzUser;
        if (accessTokenDOs != null) {
            for (AccessTokenDO accessTokenDO : accessTokenDOs) {
                // Clear cache with AccessTokenDO
                authzUser = accessTokenDO.getAuthzUser();
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser, OAuth2Util.buildScopeString(accessTokenDO.getScope()), "NONE");
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser, OAuth2Util.buildScopeString(accessTokenDO.getScope()));
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser);
                OAuthUtil.clearOAuthCache(accessTokenDO.getAccessToken());
                Cache restApiTokenCache = CacheProvider.getRESTAPITokenCache();
                if (restApiTokenCache != null) {
                    restApiTokenCache.remove(accessTokenDO.getAccessToken());
                }
                AccessTokenDO scopedToken = null;
                try {
                    // Retrieve latest access token for particular client, user and scope combination if
                    // its ACTIVE or EXPIRED.
                    scopedToken = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(appDTO.getOauthConsumerKey(), authenticatedUser, userStoreDomain, OAuth2Util.buildScopeString(accessTokenDO.getScope()), true);
                } catch (IdentityOAuth2Exception e) {
                    log.error("Error while retrieving scoped access tokens for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                }
                if (scopedToken != null) {
                    // Revoking token from database
                    try {
                        OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().revokeAccessTokens(new String[] { scopedToken.getAccessToken() });
                    } catch (IdentityOAuth2Exception e) {
                        log.error("Error while revoking access tokens related for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                    }
                    // Revoking the oauth consent from database.
                    try {
                        OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().revokeOAuthConsentByApplicationAndUser(authzUser.getAuthenticatedSubjectIdentifier(), tenantDomain, username);
                    } catch (IdentityOAuth2Exception e) {
                        log.error("Error while revoking access tokens related for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                    }
                }
            }
        }
    }
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) APIMgtDAOException(org.wso2.carbon.apimgt.api.APIMgtDAOException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SystemApplicationDTO(org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO) SystemApplicationDAO(org.wso2.carbon.apimgt.impl.dao.SystemApplicationDAO) Cache(javax.cache.Cache)

Example 20 with SessionContext

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

the class FrameworkUtils method addSessionContextToCache.

/**
 * @deprecated Use the {@link #addSessionContextToCache(String, SessionContext, String)}
 *
 * @param key
 * @param sessionContext
 */
@Deprecated
public static void addSessionContextToCache(String key, SessionContext sessionContext) {
    SessionContextCacheKey cacheKey = new SessionContextCacheKey(key);
    SessionContextCacheEntry cacheEntry = new SessionContextCacheEntry();
    Map<String, SequenceConfig> seqData = sessionContext.getAuthenticatedSequences();
    if (seqData != null) {
        for (Entry<String, SequenceConfig> entry : seqData.entrySet()) {
            if (entry.getValue() != null) {
                entry.getValue().getAuthenticatedUser().setUserAttributes(null);
                entry.getValue().setAuthenticationGraph(null);
            }
        }
    }
    Object authenticatedUserObj = sessionContext.getProperty(FrameworkConstants.AUTHENTICATED_USER);
    if (authenticatedUserObj instanceof AuthenticatedUser) {
        AuthenticatedUser authenticatedUser = (AuthenticatedUser) authenticatedUserObj;
        cacheEntry.setLoggedInUser(authenticatedUser.getAuthenticatedSubjectIdentifier());
    }
    cacheEntry.setContext(sessionContext);
    SessionContextCache.getInstance().addToCache(cacheKey, cacheEntry);
}
Also used : SessionContextCacheEntry(org.wso2.carbon.identity.application.authentication.framework.cache.SessionContextCacheEntry) SessionContextCacheKey(org.wso2.carbon.identity.application.authentication.framework.cache.SessionContextCacheKey) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) JSONObject(org.json.JSONObject) 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