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);
}
}
}
}
}
}
use of org.wso2.carbon.identity.application.authentication.framework.context.SessionContext in project carbon-identity-framework by wso2.
the class FrameworkUtils method triggerSessionExpireEvent.
/**
* Trigger SESSION_EXPIRE event on session expiry due to a session idle timeout or a remember me session time out.
*
* @param request HttpServletRequest.
* @param context Authentication context.
* @param sessionContext Session context.
* @throws FrameworkException Error in triggering the session expiry event.
*/
private static void triggerSessionExpireEvent(HttpServletRequest request, AuthenticationContext context, SessionContext sessionContext) throws FrameworkException {
AuthenticatedUser authenticatedUser = new AuthenticatedUser();
if (sessionContext != null) {
Object authenticatedUserObj = sessionContext.getProperty(FrameworkConstants.AUTHENTICATED_USER);
if (authenticatedUserObj instanceof AuthenticatedUser) {
authenticatedUser = (AuthenticatedUser) authenticatedUserObj;
}
context.setSubject(authenticatedUser);
IdentityEventService eventService = FrameworkServiceDataHolder.getInstance().getIdentityEventService();
try {
Map<String, Object> eventProperties = new HashMap<>();
eventProperties.put(IdentityEventConstants.EventProperty.REQUEST, request);
eventProperties.put(IdentityEventConstants.EventProperty.CONTEXT, context);
eventProperties.put(IdentityEventConstants.EventProperty.SESSION_CONTEXT, sessionContext);
Map<String, Object> paramMap = new HashMap<>();
paramMap.put(FrameworkConstants.AnalyticsAttributes.USER, authenticatedUser);
paramMap.put(FrameworkConstants.AnalyticsAttributes.SESSION_ID, context.getSessionIdentifier());
Map<String, Object> unmodifiableParamMap = Collections.unmodifiableMap(paramMap);
eventProperties.put(IdentityEventConstants.EventProperty.PARAMS, unmodifiableParamMap);
Event event = new Event(IdentityEventConstants.EventName.SESSION_EXPIRE.name(), eventProperties);
eventService.handleEvent(event);
} catch (IdentityEventException e) {
throw new FrameworkException("Error in triggering session expire event for the session: " + context.getSessionIdentifier() + " of user: " + authenticatedUser.toFullQualifiedUsername(), e);
}
}
}
use of org.wso2.carbon.identity.application.authentication.framework.context.SessionContext in project carbon-identity-framework by wso2.
the class SessionManagementService method removeMySession.
/**
* Terminates the requested session, after validating whether the session belongs to the logged in user.
* @deprecated Use UserSessionManagementService to terminate the session of the current user
* {@link org.wso2.carbon.identity.application.authentication.framework.UserSessionManagementService
* #terminateSessionBySessionId(String, String)}
* @param sessionId
* @return
*/
public boolean removeMySession(String sessionId) {
if (StringUtils.isBlank(sessionId)) {
return false;
}
SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(sessionId, FrameworkUtils.getLoginTenantDomainFromContext());
// Check whether the session belongs to the logged in user.
CarbonContext carbonContext = CarbonContext.getThreadLocalCarbonContext();
String username = carbonContext.getUsername();
// Extract the user store domain if there is any or set to 'PRIMARY'.
String userStoreDomain = "PRIMARY";
username = UserCoreUtil.removeDomainFromName(username);
AuthenticatedUser authenticatedUser = (AuthenticatedUser) sessionContext.getProperty(FrameworkConstants.AUTHENTICATED_USER);
if (username.equals(authenticatedUser.getUserName()) && userStoreDomain.equals(authenticatedUser.getUserStoreDomain()) && carbonContext.getTenantDomain().equals(authenticatedUser.getTenantDomain())) {
ServerSessionManagementService serverSessionManagementService = FrameworkServiceDataHolder.getInstance().getServerSessionManagementService();
return serverSessionManagementService.removeSession(sessionId);
} else {
// TODO : Handle federated scenario.
log.warn(String.format("Trying to terminate a session which does not belong to logged in user (%s). " + "This might be an attempt for a security breach", username));
return false;
}
}
use of org.wso2.carbon.identity.application.authentication.framework.context.SessionContext in project carbon-identity-framework by wso2.
the class DefaultAuthenticationRequestHandler method setAuthenticatedIDPsOfApp.
private void setAuthenticatedIDPsOfApp(SessionContext sessionContext, Map<String, AuthenticatedIdPData> authenticatedIdPs, String applicationName) throws FrameworkException {
if (log.isDebugEnabled()) {
log.debug("Getting current authenticatedIDPs of the application from authentication context and setting " + "it into session context for application: " + applicationName);
}
Map<String, AuthenticatedIdPData> authenticatedIdPDataMap = new HashMap<>();
for (Map.Entry<String, AuthenticatedIdPData> entry : authenticatedIdPs.entrySet()) {
try {
AuthenticatedIdPData authenticatedIdpData = (AuthenticatedIdPData) entry.getValue().clone();
authenticatedIdPDataMap.put(authenticatedIdpData.getIdpName(), authenticatedIdpData);
} catch (CloneNotSupportedException e) {
String errorMsg = "Error while cloning AuthenticatedIdPData object.";
throw new FrameworkException(errorMsg, e);
}
}
sessionContext.setAuthenticatedIdPsOfApp(applicationName, authenticatedIdPDataMap);
}
use of org.wso2.carbon.identity.application.authentication.framework.context.SessionContext in project carbon-identity-framework by wso2.
the class DefaultAuthenticationRequestHandler method concludeFlow.
/**
* Sends the response to the servlet that initiated the authentication flow
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
protected void concludeFlow(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws FrameworkException {
if (log.isDebugEnabled()) {
log.debug("Concluding the Authentication Flow");
}
SequenceConfig sequenceConfig = context.getSequenceConfig();
sequenceConfig.setCompleted(false);
AuthenticationResult authenticationResult = new AuthenticationResult();
boolean isAuthenticated = context.isRequestAuthenticated();
authenticationResult.setAuthenticated(isAuthenticated);
String authenticatedUserTenantDomain = getAuthenticatedUserTenantDomain(context, authenticationResult);
authenticationResult.setSaaSApp(sequenceConfig.getApplicationConfig().isSaaSApp());
if (isAuthenticated) {
if (!sequenceConfig.getApplicationConfig().isSaaSApp()) {
String spTenantDomain = context.getTenantDomain();
String userTenantDomain = sequenceConfig.getAuthenticatedUser().getTenantDomain();
if (StringUtils.isNotEmpty(userTenantDomain)) {
if (StringUtils.isNotEmpty(spTenantDomain) && !spTenantDomain.equals(userTenantDomain)) {
throw new FrameworkException("Service Provider tenant domain must be equal to user tenant " + "domain for non-SaaS applications");
}
}
}
authenticationResult.setSubject(new AuthenticatedUser(sequenceConfig.getAuthenticatedUser()));
ApplicationConfig appConfig = sequenceConfig.getApplicationConfig();
if (appConfig.getServiceProvider().getLocalAndOutBoundAuthenticationConfig().isAlwaysSendBackAuthenticatedListOfIdPs()) {
authenticationResult.setAuthenticatedIdPs(sequenceConfig.getAuthenticatedIdPs());
}
// SessionContext is retained across different SP requests in the same browser session.
// it is tracked by a cookie
SessionContext sessionContext = null;
String commonAuthCookie = null;
String sessionContextKey = null;
String analyticsSessionAction = null;
// When getting the cookie, it will not give the path. When paths are tenant qualified, it will only give
// the cookies matching that path.
Cookie authCookie = FrameworkUtils.getAuthCookie(request);
// Force authentication requires the creation of a new session. Therefore skip using the existing session
if (authCookie != null && !context.isForceAuthenticate()) {
commonAuthCookie = authCookie.getValue();
if (commonAuthCookie != null) {
sessionContextKey = DigestUtils.sha256Hex(commonAuthCookie);
sessionContext = FrameworkUtils.getSessionContextFromCache(sessionContextKey, context.getLoginTenantDomain());
}
}
String applicationTenantDomain = getApplicationTenantDomain(context);
// session context may be null when cache expires therefore creating new cookie as well.
if (sessionContext != null) {
analyticsSessionAction = FrameworkConstants.AnalyticsAttributes.SESSION_UPDATE;
sessionContext.getAuthenticatedSequences().put(appConfig.getApplicationName(), sequenceConfig);
sessionContext.getAuthenticatedIdPs().putAll(context.getCurrentAuthenticatedIdPs());
if (!context.isPassiveAuthenticate()) {
setAuthenticatedIDPsOfApp(sessionContext, context.getCurrentAuthenticatedIdPs(), appConfig.getApplicationName());
}
sessionContext.getSessionAuthHistory().resetHistory(AuthHistory.merge(sessionContext.getSessionAuthHistory().getHistory(), context.getAuthenticationStepHistory()));
populateAuthenticationContextHistory(authenticationResult, context, sessionContext);
long updatedSessionTime = System.currentTimeMillis();
if (!context.isPreviousAuthTime()) {
sessionContext.addProperty(FrameworkConstants.UPDATED_TIMESTAMP, updatedSessionTime);
}
authenticationResult.addProperty(FrameworkConstants.AnalyticsAttributes.SESSION_ID, sessionContextKey);
List<AuthenticationContextProperty> authenticationContextProperties = new ArrayList<>();
// Authentication context properties from already authenticated IdPs
if (sessionContext.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES) != null) {
List<AuthenticationContextProperty> existingAuthenticationContextProperties = (List<AuthenticationContextProperty>) sessionContext.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES);
for (AuthenticationContextProperty contextProperty : existingAuthenticationContextProperties) {
for (StepConfig stepConfig : context.getSequenceConfig().getStepMap().values()) {
if (stepConfig.getAuthenticatedIdP().equals(contextProperty.getIdPName())) {
authenticationContextProperties.add(contextProperty);
break;
}
}
}
}
Long createdTime = (Long) sessionContext.getProperty(FrameworkConstants.CREATED_TIMESTAMP);
if (createdTime != null) {
authenticationResult.addProperty(FrameworkConstants.CREATED_TIMESTAMP, createdTime);
}
// Authentication context properties received from newly authenticated IdPs
if (context.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES) != null) {
authenticationContextProperties.addAll((List<AuthenticationContextProperty>) context.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES));
if (sessionContext.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES) == null) {
sessionContext.addProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES, authenticationContextProperties);
} else {
List<AuthenticationContextProperty> existingAuthenticationContextProperties = (List<AuthenticationContextProperty>) sessionContext.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES);
existingAuthenticationContextProperties.addAll((List<AuthenticationContextProperty>) context.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES));
}
}
if (!authenticationContextProperties.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("AuthenticationContextProperties are available.");
}
authenticationResult.addProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES, authenticationContextProperties);
}
FrameworkUtils.updateSessionLastAccessTimeMetadata(sessionContextKey, updatedSessionTime);
/*
* In the default configuration, the expiry time of the commonAuthCookie is fixed when rememberMe
* option is selected. With this config, the expiry time will increase at every authentication.
*/
if (sessionContext.isRememberMe() && Boolean.parseBoolean(IdentityUtil.getProperty(IdentityConstants.ServerConfig.EXTEND_REMEMBER_ME_SESSION_ON_AUTH))) {
context.setRememberMe(sessionContext.isRememberMe());
setAuthCookie(request, response, context, commonAuthCookie, applicationTenantDomain);
}
if (context.getRuntimeClaims().size() > 0) {
sessionContext.addProperty(FrameworkConstants.RUNTIME_CLAIMS, context.getRuntimeClaims());
}
handleSessionContextUpdate(context.getRequestType(), sessionContextKey, sessionContext, request, response, context);
// TODO add to cache?
// store again. when replicate cache is used. this may be needed.
FrameworkUtils.addSessionContextToCache(sessionContextKey, sessionContext, applicationTenantDomain, context.getLoginTenantDomain());
} else {
analyticsSessionAction = FrameworkConstants.AnalyticsAttributes.SESSION_CREATE;
sessionContext = new SessionContext();
// To identify first login
context.setProperty(FrameworkConstants.AnalyticsAttributes.IS_INITIAL_LOGIN, true);
sessionContext.getAuthenticatedSequences().put(appConfig.getApplicationName(), sequenceConfig);
sessionContext.setAuthenticatedIdPs(context.getCurrentAuthenticatedIdPs());
setAuthenticatedIDPsOfApp(sessionContext, context.getCurrentAuthenticatedIdPs(), appConfig.getApplicationName());
sessionContext.setRememberMe(context.isRememberMe());
if (context.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES) != null) {
if (log.isDebugEnabled()) {
log.debug("AuthenticationContextProperties are available.");
}
authenticationResult.addProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES, context.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES));
// Add to session context
sessionContext.addProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES, context.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES));
}
String sessionKey = UUIDGenerator.generateUUID();
sessionContextKey = DigestUtils.sha256Hex(sessionKey);
sessionContext.addProperty(FrameworkConstants.AUTHENTICATED_USER, authenticationResult.getSubject());
sessionContext.addProperty(FrameworkUtils.TENANT_DOMAIN, context.getLoginTenantDomain());
Long createdTimeMillis = System.currentTimeMillis();
sessionContext.addProperty(FrameworkConstants.CREATED_TIMESTAMP, createdTimeMillis);
authenticationResult.addProperty(FrameworkConstants.CREATED_TIMESTAMP, createdTimeMillis);
authenticationResult.addProperty(FrameworkConstants.AnalyticsAttributes.SESSION_ID, sessionContextKey);
sessionContext.getSessionAuthHistory().resetHistory(AuthHistory.merge(sessionContext.getSessionAuthHistory().getHistory(), context.getAuthenticationStepHistory()));
populateAuthenticationContextHistory(authenticationResult, context, sessionContext);
if (context.getRuntimeClaims().size() > 0) {
sessionContext.addProperty(FrameworkConstants.RUNTIME_CLAIMS, context.getRuntimeClaims());
}
handleInboundSessionCreate(context.getRequestType(), sessionContextKey, sessionContext, request, response, context);
FrameworkUtils.addSessionContextToCache(sessionContextKey, sessionContext, applicationTenantDomain, context.getLoginTenantDomain());
setAuthCookie(request, response, context, sessionKey, applicationTenantDomain);
if (FrameworkServiceDataHolder.getInstance().isUserSessionMappingEnabled()) {
try {
storeSessionMetaData(sessionContextKey, request);
} catch (UserSessionException e) {
log.error("Storing session meta data failed.", e);
}
}
}
if (authenticatedUserTenantDomain == null) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
}
if (FrameworkServiceDataHolder.getInstance().isUserSessionMappingEnabled()) {
try {
storeSessionData(context, sessionContextKey);
} catch (UserSessionException e) {
throw new FrameworkException("Error while storing session details of the authenticated user to " + "the database", e);
}
}
// store the saml index with the session context key for the single logout.
if (context.getAuthenticationStepHistory() != null) {
UserSessionStore userSessionStore = UserSessionStore.getInstance();
for (AuthHistory authHistory : context.getAuthenticationStepHistory()) {
if (StringUtils.isNotBlank(authHistory.getIdpSessionIndex()) && StringUtils.isNotBlank(authHistory.getIdpName())) {
try {
if (!userSessionStore.hasExistingFederatedAuthSession(authHistory.getIdpSessionIndex())) {
userSessionStore.storeFederatedAuthSessionInfo(sessionContextKey, authHistory);
} else {
if (log.isDebugEnabled()) {
log.debug(String.format("Federated auth session with the id: %s already exists", authHistory.getIdpSessionIndex()));
}
userSessionStore.updateFederatedAuthSessionInfo(sessionContextKey, authHistory);
}
} catch (UserSessionException e) {
throw new FrameworkException("Error while storing federated authentication session details " + "of the authenticated user to the database", e);
}
}
}
}
FrameworkUtils.publishSessionEvent(sessionContextKey, request, context, sessionContext, sequenceConfig.getAuthenticatedUser(), analyticsSessionAction);
publishAuthenticationSuccess(request, context, sequenceConfig.getAuthenticatedUser());
}
// authenticator in multi steps scenario. Ex. Fido
if (FrameworkUtils.getCacheDisabledAuthenticators().contains(context.getRequestType()) && (response instanceof CommonAuthResponseWrapper) && !((CommonAuthResponseWrapper) response).isWrappedByFramework()) {
// Set the result as request attribute
request.setAttribute("sessionDataKey", context.getCallerSessionKey());
addAuthenticationResultToRequest(request, authenticationResult);
} else {
FrameworkUtils.addAuthenticationResultToCache(context.getCallerSessionKey(), authenticationResult);
}
/*
* TODO Cache retaining is a temporary fix. Remove after Google fixes
* http://code.google.com/p/gdata-issues/issues/detail?id=6628
*/
String retainCache = System.getProperty("retainCache");
if (retainCache == null) {
FrameworkUtils.removeAuthenticationContextFromCache(context.getContextIdentifier());
}
sendResponse(request, response, context);
}
Aggregations