Search in sources :

Example 1 with CommonAuthResponseWrapper

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

the class DefaultStepHandler method getRedirectUrl.

private String getRedirectUrl(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context, String authenticatorNames, String showAuthFailureReason, String retryParam, String loginPage) throws IOException, URISyntaxException {
    IdentityErrorMsgContext errorContext = IdentityUtil.getIdentityErrorMsg();
    IdentityUtil.clearIdentityErrorMsg();
    retryParam = handleIdentifierFirstLogin(context, retryParam);
    String otp = (String) context.getProperty(FrameworkConstants.PASSWORD_PROPERTY);
    context.getProperties().remove(FrameworkConstants.PASSWORD_PROPERTY);
    // If recaptcha is enabled and the Basic Authenticator is in the authenticator list for this page, the recaptcha
    // params set by the Basic Authenticator need to be added to new URL generated for the multi option page.
    // Currently, there is no method to check whether recaptcha has been enabled without manually reading the
    // captcha-config.properties file. Hence, this fragment is always executed without the check, but will not
    // alter the final URL if recaptcha is not enabled. This filters out the recaptcha params from the redirect
    // URL previously set by an authenticator and generates a query string to be appended to the new redirect URL.
    StringBuilder reCaptchaParamString = new StringBuilder("");
    StringBuilder errorParamString = new StringBuilder("");
    String basicAuthRedirectUrl = ((CommonAuthResponseWrapper) response).getRedirectURL();
    if (StringUtils.isNotBlank(basicAuthRedirectUrl)) {
        List<NameValuePair> queryParameters = new URIBuilder(basicAuthRedirectUrl).getQueryParams();
        List<NameValuePair> reCaptchaParameters = queryParameters.stream().filter(param -> FrameworkConstants.RECAPTCHA_API_PARAM.equals(param.getName()) || FrameworkConstants.RECAPTCHA_KEY_PARAM.equals(param.getName()) || FrameworkConstants.RECAPTCHA_PARAM.equals(param.getName()) || FrameworkConstants.RECAPTCHA_RESEND_CONFIRMATION_PARAM.equals(param.getName())).collect(Collectors.toList());
        for (NameValuePair reCaptchaParam : reCaptchaParameters) {
            reCaptchaParamString.append("&").append(reCaptchaParam.getName()).append("=").append(reCaptchaParam.getValue());
        }
        if (errorContext == null) {
            List<NameValuePair> errorContextParams = queryParameters.stream().filter(param -> FrameworkConstants.ERROR_CODE.equals(param.getName()) || FrameworkConstants.LOCK_REASON.equals(param.getName()) || FrameworkConstants.REMAINING_ATTEMPTS.equals(param.getName()) || FrameworkConstants.FAILED_USERNAME.equals(param.getName())).collect(Collectors.toList());
            if (errorContextParams.size() > 0) {
                for (NameValuePair errorParams : errorContextParams) {
                    errorParamString.append("&").append(errorParams.getName()).append("=").append(errorParams.getValue());
                }
            }
        }
    }
    if (showAuthFailureReason != null && "true".equals(showAuthFailureReason)) {
        if (errorContext != null) {
            String errorCode = errorContext.getErrorCode();
            String reason = null;
            if (errorCode.contains(":")) {
                String[] errorCodeReason = errorCode.split(":", 2);
                if (errorCodeReason.length > 1) {
                    errorCode = errorCodeReason[0];
                    reason = errorCodeReason[1];
                }
            }
            int remainingAttempts = errorContext.getMaximumLoginAttempts() - errorContext.getFailedLoginAttempts();
            if (LOG.isDebugEnabled()) {
                StringBuilder debugString = new StringBuilder();
                debugString.append("Identity error message context is not null. Error details are as follows.");
                debugString.append("errorCode : " + errorCode + "\n");
                debugString.append("username : " + request.getParameter("username") + "\n");
                debugString.append("remainingAttempts : " + remainingAttempts);
                LOG.debug(debugString.toString());
            }
            if (UserCoreConstants.ErrorCode.INVALID_CREDENTIAL.equals(errorCode)) {
                retryParam = retryParam + "&errorCode=" + errorCode + "&failedUsername=" + URLEncoder.encode(request.getParameter("username"), "UTF-8") + "&remainingAttempts=" + remainingAttempts;
                return response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString();
            } else if (UserCoreConstants.ErrorCode.USER_IS_LOCKED.equals(errorCode)) {
                String redirectURL;
                if (remainingAttempts == 0) {
                    if (StringUtils.isBlank(reason)) {
                        redirectURL = response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&errorCode=" + errorCode + "&failedUsername=" + URLEncoder.encode(request.getParameter("username"), "UTF-8") + "&remainingAttempts=0" + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString;
                    } else {
                        redirectURL = response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&errorCode=" + errorCode + "&lockedReason=" + reason + "&failedUsername=" + URLEncoder.encode(request.getParameter("username"), "UTF-8") + "&remainingAttempts=0" + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString;
                    }
                } else {
                    if (StringUtils.isBlank(reason)) {
                        redirectURL = response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&errorCode=" + errorCode + "&failedUsername=" + URLEncoder.encode(request.getParameter("username"), "UTF-8") + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString;
                    } else {
                        redirectURL = response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&errorCode=" + errorCode + "&lockedReason=" + reason + "&failedUsername=" + URLEncoder.encode(request.getParameter("username"), "UTF-8") + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString();
                    }
                }
                return redirectURL;
            } else if (IdentityCoreConstants.USER_ACCOUNT_NOT_CONFIRMED_ERROR_CODE.equals(errorCode)) {
                retryParam = "&authFailure=true&authFailureMsg=account.confirmation.pending";
                String username = request.getParameter("username");
                Object domain = IdentityUtil.threadLocalProperties.get().get(RE_CAPTCHA_USER_DOMAIN);
                if (domain != null) {
                    username = IdentityUtil.addDomainToName(username, domain.toString());
                }
                retryParam = retryParam + "&errorCode=" + errorCode + "&failedUsername=" + URLEncoder.encode(username, "UTF-8");
                return response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString();
            } else if (IdentityCoreConstants.USER_INVALID_CREDENTIALS.equals(errorCode)) {
                retryParam = "&authFailure=true&authFailureMsg=login.fail.message";
                String username = request.getParameter("username");
                Object domain = IdentityUtil.threadLocalProperties.get().get(RE_CAPTCHA_USER_DOMAIN);
                if (domain != null) {
                    username = IdentityUtil.addDomainToName(username, domain.toString());
                }
                retryParam = retryParam + "&errorCode=" + errorCode + "&failedUsername=" + URLEncoder.encode(username, "UTF-8");
                return response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString();
            } else if (IdentityCoreConstants.ADMIN_FORCED_USER_PASSWORD_RESET_VIA_OTP_ERROR_CODE.equals(errorCode)) {
                String username = request.getParameter("username");
                return response.encodeRedirectURL(("accountrecoveryendpoint/confirmrecovery.do?" + context.getContextIdIncludedQueryParams())) + "&username=" + URLEncoder.encode(username, "UTF-8") + "&confirmation=" + otp + reCaptchaParamString.toString();
            } else {
                if (StringUtils.isNotBlank(retryParam) && StringUtils.isNotBlank(reason)) {
                    retryParam = "&authFailure=true&authFailureMsg=" + URLEncoder.encode(reason, "UTF-8");
                }
                retryParam += "&errorCode=" + errorCode + "&failedUsername=" + URLEncoder.encode(request.getParameter("username"), "UTF-8");
                return response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString();
            }
        } else {
            return response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString() + errorParamString;
        }
    } else {
        String errorCode = errorContext != null ? errorContext.getErrorCode() : null;
        if (UserCoreConstants.ErrorCode.USER_IS_LOCKED.equals(errorCode)) {
            String redirectURL;
            redirectURL = response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&failedUsername=" + URLEncoder.encode(request.getParameter("username"), "UTF-8") + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString();
            return redirectURL;
        } else if (IdentityCoreConstants.ADMIN_FORCED_USER_PASSWORD_RESET_VIA_OTP_ERROR_CODE.equals(errorCode)) {
            String username = request.getParameter("username");
            return response.encodeRedirectURL(("accountrecoveryendpoint/confirmrecovery.do?" + context.getContextIdIncludedQueryParams())) + "&username=" + URLEncoder.encode(username, "UTF-8") + "&confirmation=" + otp + reCaptchaParamString.toString();
        } else {
            return response.encodeRedirectURL(loginPage + ("?" + context.getContextIdIncludedQueryParams())) + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + retryParam + reCaptchaParamString.toString();
        }
    }
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) FrameworkConstants(org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants) URISyntaxException(java.net.URISyntaxException) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) Map(java.util.Map) AuthenticatedIdPData(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData) IdentityErrorMsgContext(org.wso2.carbon.identity.core.model.IdentityErrorMsgContext) UserStoreClientException(org.wso2.carbon.user.core.UserStoreClientException) User(org.wso2.carbon.identity.application.common.model.User) URIBuilder(org.apache.http.client.utils.URIBuilder) AuthenticatorFlowStatus(org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus) UserSessionException(org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper) UUID(java.util.UUID) UserCoreConstants(org.wso2.carbon.user.core.UserCoreConstants) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) StepHandler(org.wso2.carbon.identity.application.authentication.framework.handler.step.StepHandler) List(java.util.List) UserSessionStore(org.wso2.carbon.identity.application.authentication.framework.store.UserSessionStore) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) FEDERATED_IDP_SESSION_ID(org.wso2.carbon.identity.base.IdentityConstants.FEDERATED_IDP_SESSION_ID) LogoutFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException) LogFactory(org.apache.commons.logging.LogFactory) NameValuePair(org.apache.http.NameValuePair) CarbonConstants(org.wso2.carbon.CarbonConstants) AuthHistory(org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory) FrameworkUtils(org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils) AuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) ExternalIdPConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ExternalIdPConfig) InvalidCredentialsException(org.wso2.carbon.identity.application.authentication.framework.exception.InvalidCredentialsException) HashMap(java.util.HashMap) DuplicatedAuthUserException(org.wso2.carbon.identity.application.authentication.framework.exception.DuplicatedAuthUserException) HttpServletRequest(javax.servlet.http.HttpServletRequest) IdentityTenantUtil(org.wso2.carbon.identity.core.util.IdentityTenantUtil) MapUtils(org.apache.commons.collections.MapUtils) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) AuthenticationFlowHandler(org.wso2.carbon.identity.application.authentication.framework.AuthenticationFlowHandler) ExceptionUtils(org.apache.commons.lang.exception.ExceptionUtils) HttpServletResponse(javax.servlet.http.HttpServletResponse) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) BASIC_AUTH_MECHANISM(org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants.BASIC_AUTH_MECHANISM) LocalApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.LocalApplicationAuthenticator) IOException(java.io.IOException) AuthenticatorConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig) ApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator) URLEncoder(java.net.URLEncoder) FileBasedConfigurationBuilder(org.wso2.carbon.identity.application.authentication.framework.config.builder.FileBasedConfigurationBuilder) IdentityCoreConstants(org.wso2.carbon.identity.core.util.IdentityCoreConstants) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) ConfigurationFacade(org.wso2.carbon.identity.application.authentication.framework.config.ConfigurationFacade) IdentityUtil(org.wso2.carbon.identity.core.util.IdentityUtil) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) Log(org.apache.commons.logging.Log) CarbonUtils.isLegacyAuditLogsDisabled(org.wso2.carbon.utils.CarbonUtils.isLegacyAuditLogsDisabled) NameValuePair(org.apache.http.NameValuePair) IdentityErrorMsgContext(org.wso2.carbon.identity.core.model.IdentityErrorMsgContext) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 2 with CommonAuthResponseWrapper

use of org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper 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 CommonAuthResponseWrapper

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

the class OAuth2AuthzEndpoint method handleAuthFlowThroughFramework.

/**
 * This method use to call authentication framework directly via API other than using HTTP redirects.
 * Sending wrapper request object to doGet method since other original request doesn't exist required parameters
 * Doesn't check SUCCESS_COMPLETED since taking decision with INCOMPLETE status
 *
 * @param type authenticator type
 * @throws URISyntaxException
 * @throws InvalidRequestParentException
 * @Param type OAuthMessage
 */
private Response handleAuthFlowThroughFramework(OAuthMessage oAuthMessage, String type) throws URISyntaxException, InvalidRequestParentException {
    if (LoggerUtils.isDiagnosticLogsEnabled()) {
        Map<String, Object> params = new HashMap<>();
        params.put("clientId", oAuthMessage.getClientId());
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Forward authorization request to framework for user authentication.", "hand-over-to-framework", null);
    }
    try {
        String sessionDataKey = (String) oAuthMessage.getRequest().getAttribute(FrameworkConstants.SESSION_DATA_KEY);
        CommonAuthenticationHandler commonAuthenticationHandler = new CommonAuthenticationHandler();
        CommonAuthRequestWrapper requestWrapper = new CommonAuthRequestWrapper(oAuthMessage.getRequest());
        requestWrapper.setParameter(FrameworkConstants.SESSION_DATA_KEY, sessionDataKey);
        requestWrapper.setParameter(FrameworkConstants.RequestParams.TYPE, type);
        CommonAuthResponseWrapper responseWrapper = new CommonAuthResponseWrapper(oAuthMessage.getResponse());
        commonAuthenticationHandler.doGet(requestWrapper, responseWrapper);
        Object attribute = oAuthMessage.getRequest().getAttribute(FrameworkConstants.RequestParams.FLOW_STATUS);
        if (attribute != null) {
            if (attribute == AuthenticatorFlowStatus.INCOMPLETE) {
                if (responseWrapper.isRedirect()) {
                    return Response.status(HttpServletResponse.SC_FOUND).location(buildURI(responseWrapper.getRedirectURL())).build();
                } else {
                    return Response.status(HttpServletResponse.SC_OK).entity(responseWrapper.getContent()).build();
                }
            } else {
                return authorize(requestWrapper, responseWrapper);
            }
        } else {
            requestWrapper.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.UNKNOWN);
            return authorize(requestWrapper, responseWrapper);
        }
    } catch (ServletException | IOException | URLBuilderException e) {
        log.error("Error occurred while sending request to authentication framework.");
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", oAuthMessage.getClientId());
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Server error occurred.", "hand-over-to-framework", null);
        }
        return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).build();
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) CommonAuthenticationHandler(org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) CommonAuthRequestWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)

Example 4 with CommonAuthResponseWrapper

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

the class OAuth2AuthzEndpoint method invokeCommonauthFlow.

private void invokeCommonauthFlow(OAuthMessage oAuthMessage, CommonAuthResponseWrapper responseWrapper) throws ServletException, IOException {
    CommonAuthenticationHandler commonAuthenticationHandler = new CommonAuthenticationHandler();
    commonAuthenticationHandler.doGet(oAuthMessage.getRequest(), responseWrapper);
}
Also used : CommonAuthenticationHandler(org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler)

Example 5 with CommonAuthResponseWrapper

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

the class OIDCLogoutServlet method sendRequestToFramework.

private void sendRequestToFramework(HttpServletRequest request, HttpServletResponse response, String sessionDataKey, String type) throws ServletException, IOException {
    CommonAuthenticationHandler commonAuthenticationHandler = new CommonAuthenticationHandler();
    CommonAuthRequestWrapper requestWrapper = new CommonAuthRequestWrapper(request);
    requestWrapper.setParameter(FrameworkConstants.SESSION_DATA_KEY, sessionDataKey);
    requestWrapper.setParameter(FrameworkConstants.RequestParams.TYPE, type);
    CommonAuthResponseWrapper responseWrapper = new CommonAuthResponseWrapper(response);
    commonAuthenticationHandler.doGet(requestWrapper, responseWrapper);
    Object object = request.getAttribute(FrameworkConstants.RequestParams.FLOW_STATUS);
    if (object != null) {
        AuthenticatorFlowStatus status = (AuthenticatorFlowStatus) object;
        if (status == AuthenticatorFlowStatus.INCOMPLETE) {
            if (responseWrapper.isRedirect()) {
                response.sendRedirect(responseWrapper.getRedirectURL());
            } else if (responseWrapper.getContent().length > 0) {
                responseWrapper.write();
            }
        } else {
            handleLogoutResponseFromFramework(requestWrapper, response);
        }
    } else {
        handleLogoutResponseFromFramework(requestWrapper, response);
    }
}
Also used : CommonAuthRequestWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper) CommonAuthenticationHandler(org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler) AuthenticatorFlowStatus(org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)

Aggregations

CommonAuthResponseWrapper (org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)9 CommonAuthenticationHandler (org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler)4 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)3 FrameworkException (org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException)3 CommonAuthRequestWrapper (org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper)3 List (java.util.List)2 Map (java.util.Map)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 ServletException (javax.servlet.ServletException)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 Test (org.testng.annotations.Test)2 AuthenticatorFlowStatus (org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus)2 StepConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig)2 AuthHistory (org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory)2 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)2 UserSessionException (org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException)2 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)2