Search in sources :

Example 1 with ApplicationConfig

use of org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig in project carbon-apimgt by wso2.

the class APIConsumerImpl method getAppAttributesFromConfig.

/**
 * This method is used to get keys of custom attributes, configured by user
 *
 * @param userId user name of logged in user
 * @return Array of JSONObject, contains keys of attributes
 * @throws APIManagementException
 */
public JSONArray getAppAttributesFromConfig(String userId) throws APIManagementException {
    String tenantDomain = MultitenantUtils.getTenantDomain(userId);
    int tenantId = 0;
    try {
        tenantId = getTenantId(tenantDomain);
    } catch (UserStoreException e) {
        handleException("Error in getting tenantId of " + tenantDomain, e);
    }
    JSONArray applicationAttributes = null;
    JSONObject applicationConfig = APIUtil.getAppAttributeKeysFromRegistry(tenantDomain);
    if (applicationConfig != null) {
        applicationAttributes = (JSONArray) applicationConfig.get(APIConstants.ApplicationAttributes.ATTRIBUTES);
    } else {
        APIManagerConfiguration configuration = getAPIManagerConfiguration();
        applicationAttributes = configuration.getApplicationAttributes();
    }
    return applicationAttributes;
}
Also used : JSONObject(org.json.simple.JSONObject) UserStoreException(org.wso2.carbon.user.api.UserStoreException) JSONArray(org.json.simple.JSONArray)

Example 2 with ApplicationConfig

use of org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig 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);
}
Also used : SessionNonceCookieUtil.removeNonceCookie(org.wso2.carbon.identity.application.authentication.framework.util.SessionNonceCookieUtil.removeNonceCookie) SessionNonceCookieUtil.addNonceCookie(org.wso2.carbon.identity.application.authentication.framework.util.SessionNonceCookieUtil.addNonceCookie) SessionNonceCookieUtil.validateNonceCookie(org.wso2.carbon.identity.application.authentication.framework.util.SessionNonceCookieUtil.validateNonceCookie) Cookie(javax.servlet.http.Cookie) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) UserSessionStore(org.wso2.carbon.identity.application.authentication.framework.store.UserSessionStore) ArrayList(java.util.ArrayList) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) UserSessionException(org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException) AuthenticationResult(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult) ApplicationConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig) SessionContext(org.wso2.carbon.identity.application.authentication.framework.context.SessionContext) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) List(java.util.List) ArrayList(java.util.ArrayList) AuthHistory(org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory) AuthenticationContextProperty(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationContextProperty) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)

Example 3 with ApplicationConfig

use of org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig in project carbon-identity-framework by wso2.

the class ConsentMgtPostAuthnHandler method getSPRequestedLocalClaims.

private List<String> getSPRequestedLocalClaims(AuthenticationContext context) throws PostAuthenticationFailedException {
    List<String> spRequestedLocalClaims = new ArrayList<>();
    ApplicationConfig applicationConfig = context.getSequenceConfig().getApplicationConfig();
    if (applicationConfig == null) {
        ServiceProvider serviceProvider = getServiceProvider(context);
        String error = "Application configs are null in AuthenticationContext for SP: " + serviceProvider.getApplicationName() + " in tenant domain: " + getSPTenantDomain(serviceProvider);
        throw new PostAuthenticationFailedException("Authentication failed. Error while processing application " + "claim configurations.", error);
    }
    Map<String, String> claimMappings = applicationConfig.getRequestedClaimMappings();
    if (isNotEmpty(claimMappings) && isNotEmpty(claimMappings.values())) {
        spRequestedLocalClaims = new ArrayList<>(claimMappings.values());
    }
    String subjectClaimUri = getSubjectClaimUri(applicationConfig);
    spRequestedLocalClaims.remove(subjectClaimUri);
    if (isDebugEnabled()) {
        String message = String.format("Requested claims for SP: %s - " + spRequestedLocalClaims, applicationConfig.getApplicationName());
        logDebug(message);
    }
    return spRequestedLocalClaims;
}
Also used : ApplicationConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ArrayList(java.util.ArrayList) StringUtils.defaultString(org.apache.commons.lang.StringUtils.defaultString) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException)

Example 4 with ApplicationConfig

use of org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig in project carbon-identity-framework by wso2.

the class DefaultSequenceHandlerUtils method getSPStandardDialect.

/**
 * Get the standard claim dialect of the service provider in the
 * authentication context.
 *
 * @param context AuthenticationContext.
 * @return The claim dialect of the service provider.
 */
private static String getSPStandardDialect(AuthenticationContext context) {
    ApplicationConfig appConfig = context.getSequenceConfig().getApplicationConfig();
    String spStandardDialect;
    if (context.getProperties().containsKey(FrameworkConstants.SP_STANDARD_DIALECT)) {
        spStandardDialect = (String) context.getProperty(FrameworkConstants.SP_STANDARD_DIALECT);
    } else {
        spStandardDialect = FrameworkUtils.getStandardDialect(context.getRequestType(), appConfig);
    }
    return spStandardDialect;
}
Also used : ApplicationConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig)

Example 5 with ApplicationConfig

use of org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig in project carbon-identity-framework by wso2.

the class DefaultClaimHandler method setSubjectClaim.

/**
 * Set authenticated user's SP Subject Claim URI as a property
 */
private void setSubjectClaim(AuthenticatedUser authenticatedUser, AbstractUserStoreManager userStore, Map<String, String> attributesMap, String spStandardDialect, AuthenticationContext context) {
    String subjectURI = context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri();
    ApplicationConfig applicationConfig = context.getSequenceConfig().getApplicationConfig();
    ServiceProvider serviceProvider = applicationConfig.getServiceProvider();
    ClaimConfig claimConfig = serviceProvider.getClaimConfig();
    boolean isLocalClaimDialect = claimConfig.isLocalClaimDialect();
    Map<String, String> spToLocalClaimMappings = applicationConfig.getClaimMappings();
    if (subjectURI != null) {
        if (!isLocalClaimDialect && spStandardDialect != null) {
            if (spToLocalClaimMappings != null) {
                subjectURI = spToLocalClaimMappings.get(subjectURI);
            }
        }
        if (attributesMap.get(subjectURI) != null) {
            context.setProperty(SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE, attributesMap.get(subjectURI));
            if (log.isDebugEnabled()) {
                log.debug("Setting \'ServiceProviderSubjectClaimValue\' property value from " + "attribute map " + attributesMap.get(subjectURI));
            }
        } else {
            log.debug("Subject claim not found among attributes");
        }
        // if federated case return
        if (authenticatedUser == null || userStore == null || authenticatedUser.isFederatedUser()) {
            if (log.isDebugEnabled()) {
                log.debug("User id or user store \'NULL\'. Possibly federated case");
            }
            return;
        }
        // standard dialect
        if (spStandardDialect != null) {
            setSubjectClaimForStandardDialect(authenticatedUser, userStore, context, subjectURI);
        }
    }
}
Also used : ApplicationConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig) ClaimConfig(org.wso2.carbon.identity.application.common.model.ClaimConfig) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider)

Aggregations

ApplicationConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig)25 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)11 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)9 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)7 Test (org.testng.annotations.Test)7 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)6 ArrayList (java.util.ArrayList)5 FrameworkException (org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException)5 HashMap (java.util.HashMap)4 StringUtils.defaultString (org.apache.commons.lang.StringUtils.defaultString)4 AuthenticatorConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig)4 StepConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig)4 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)4 ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)4 PostAuthenticationFailedException (org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException)3 LocalAndOutboundAuthenticationConfig (org.wso2.carbon.identity.application.common.model.LocalAndOutboundAuthenticationConfig)3 List (java.util.List)2 Map (java.util.Map)2 ApplicationAuthenticator (org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator)2 ExternalIdPConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.ExternalIdPConfig)2