Search in sources :

Example 16 with Authenticator

use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.

the class DefaultStepHandler method doAuthentication.

protected void doAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context, AuthenticatorConfig authenticatorConfig) throws FrameworkException {
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    int currentStep = context.getCurrentStep();
    StepConfig stepConfig = sequenceConfig.getStepMap().get(currentStep);
    ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator();
    if (authenticator == null) {
        LOG.error("Authenticator is null for AuthenticatorConfig: " + authenticatorConfig.getName());
        return;
    }
    String idpName = FrameworkConstants.LOCAL_IDP_NAME;
    if (context.getExternalIdP() != null && authenticator instanceof FederatedApplicationAuthenticator) {
        idpName = context.getExternalIdP().getIdPName();
    }
    try {
        context.setAuthenticatorProperties(FrameworkUtils.getAuthenticatorPropertyMapFromIdP(context.getExternalIdP(), authenticator.getName()));
        AuthenticatorFlowStatus status = authenticator.process(request, response, context);
        request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, status);
        if (LOG.isDebugEnabled()) {
            LOG.debug(authenticator.getName() + " returned: " + status.toString());
        }
        if (status == AuthenticatorFlowStatus.INCOMPLETE) {
            context.setCurrentAuthenticator(authenticator.getName());
            if (LOG.isDebugEnabled()) {
                LOG.debug(authenticator.getName() + " is redirecting");
            }
            return;
        }
        if (authenticator instanceof FederatedApplicationAuthenticator) {
            if (context.getSubject().getUserName() == null) {
                // Set subject identifier as the default username for federated users
                String authenticatedSubjectIdentifier = context.getSubject().getAuthenticatedSubjectIdentifier();
                context.getSubject().setUserName(authenticatedSubjectIdentifier);
            }
            if (context.getSubject().getFederatedIdPName() == null && context.getExternalIdP() != null) {
                // Setting identity provider's name
                context.getSubject().setFederatedIdPName(idpName);
            }
            if (context.getSubject().getTenantDomain() == null) {
                // Setting service provider's tenant domain as the default tenant for federated users
                String tenantDomain = context.getTenantDomain();
                context.getSubject().setTenantDomain(tenantDomain);
            }
            try {
                // Check if the user id is available for the user. If the user id is not available or cannot be
                // resolved, UserIdNotFoundException is thrown.
                String userId = context.getSubject().getUserId();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("User id is available for user: " + userId);
                }
            } catch (UserIdNotFoundException e) {
                String tenantDomain = context.getSubject().getTenantDomain();
                int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
                String authenticatedSubjectIdentifier = context.getSubject().getAuthenticatedSubjectIdentifier();
                String federatedIdPName = context.getSubject().getFederatedIdPName();
                try {
                    int idpId = UserSessionStore.getInstance().getIdPId(federatedIdPName, tenantId);
                    String userId = UserSessionStore.getInstance().getFederatedUserId(authenticatedSubjectIdentifier, tenantId, idpId);
                    try {
                        if (userId == null) {
                            userId = UUID.randomUUID().toString();
                            UserSessionStore.getInstance().storeUserData(userId, authenticatedSubjectIdentifier, tenantId, idpId);
                        }
                    } catch (DuplicatedAuthUserException e1) {
                        String msg = "User authenticated is already persisted. Username: " + authenticatedSubjectIdentifier + " Tenant Domain:" + tenantDomain + " IdP: " + federatedIdPName;
                        LOG.warn(msg);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug(msg, e1);
                        }
                        // Since duplicate entry was found, let's try to get the ID again.
                        userId = UserSessionStore.getInstance().getFederatedUserId(authenticatedSubjectIdentifier, tenantId, idpId);
                    }
                    context.getSubject().setUserId(userId);
                } catch (UserSessionException e2) {
                    LOG.error("Error while resolving the user id for federated user.", e2);
                }
            }
        }
        AuthenticatedIdPData authenticatedIdPData = getAuthenticatedIdPData(context, idpName);
        // store authenticated user
        AuthenticatedUser authenticatedUser = context.getSubject();
        stepConfig.setAuthenticatedUser(authenticatedUser);
        authenticatedIdPData.setUser(authenticatedUser);
        authenticatorConfig.setAuthenticatorStateInfo(context.getStateInfo());
        stepConfig.setAuthenticatedAutenticator(authenticatorConfig);
        // store authenticated idp
        stepConfig.setAuthenticatedIdP(idpName);
        authenticatedIdPData.setIdpName(idpName);
        authenticatedIdPData.addAuthenticator(authenticatorConfig);
        // add authenticated idp data to the session wise map
        context.getCurrentAuthenticatedIdPs().put(idpName, authenticatedIdPData);
        // Add SAML federated idp session index into the authentication step history.
        String idpSessionIndex = null;
        String parameterName = FEDERATED_IDP_SESSION_ID + idpName;
        AuthHistory authHistory = new AuthHistory(authenticator.getName(), idpName);
        if (context.getParameters() != null && context.getParameters().containsKey(parameterName)) {
            Object idpSessionIndexParamValue = context.getParameter(parameterName);
            if (idpSessionIndexParamValue != null) {
                idpSessionIndex = idpSessionIndexParamValue.toString();
            }
        }
        if (StringUtils.isNotBlank(context.getCurrentAuthenticator()) && StringUtils.isNotBlank(idpSessionIndex)) {
            authHistory.setIdpSessionIndex(idpSessionIndex);
            authHistory.setRequestType(context.getRequestType());
        }
        Serializable startTime = context.getAnalyticsData(FrameworkConstants.AnalyticsData.CURRENT_AUTHENTICATOR_START_TIME);
        if (startTime instanceof Long) {
            authHistory.setDuration((long) startTime - System.currentTimeMillis());
        }
        authHistory.setSuccess(true);
        context.addAuthenticationStepHistory(authHistory);
        String initiator = null;
        if (stepConfig.getAuthenticatedUser() != null) {
            initiator = stepConfig.getAuthenticatedUser().toFullQualifiedUsername();
        }
        String data = "Step: " + stepConfig.getOrder() + ", IDP: " + stepConfig.getAuthenticatedIdP() + ", Authenticator:" + stepConfig.getAuthenticatedAutenticator().getName();
        if (!isLegacyAuditLogsDisabled()) {
            audit.info(String.format(AUDIT_MESSAGE, initiator, "Authenticate", "ApplicationAuthenticationFramework", data, SUCCESS));
        }
    } catch (InvalidCredentialsException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("A login attempt was failed due to invalid credentials", e);
        }
        String data = "Step: " + stepConfig.getOrder() + ", IDP: " + idpName + ", Authenticator:" + authenticatorConfig.getName();
        String initiator = null;
        if (e.getUser() != null) {
            initiator = e.getUser().toFullQualifiedUsername();
        } else if (context.getSubject() != null) {
            initiator = context.getSubject().toFullQualifiedUsername();
        }
        if (!isLegacyAuditLogsDisabled()) {
            audit.warn(String.format(AUDIT_MESSAGE, initiator, "Authenticate", "ApplicationAuthenticationFramework", data, FAILURE));
        }
        handleFailedAuthentication(request, response, context, authenticatorConfig, e.getUser());
    } catch (AuthenticationFailedException e) {
        IdentityErrorMsgContext errorContext = IdentityUtil.getIdentityErrorMsg();
        if (errorContext != null) {
            Throwable rootCause = ExceptionUtils.getRootCause(e);
            if (!IdentityCoreConstants.ADMIN_FORCED_USER_PASSWORD_RESET_VIA_OTP_ERROR_CODE.equals(errorContext.getErrorCode()) && !(rootCause instanceof UserStoreClientException) && !IdentityCoreConstants.USER_ACCOUNT_LOCKED_ERROR_CODE.equals(errorContext.getErrorCode()) && !IdentityCoreConstants.USER_ACCOUNT_DISABLED_ERROR_CODE.equals(errorContext.getErrorCode()) && !IdentityCoreConstants.USER_ACCOUNT_NOT_CONFIRMED_ERROR_CODE.equals(errorContext.getErrorCode())) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Authentication failed exception!", e);
                }
                LOG.error("Authentication failed exception! " + e.getMessage());
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Authentication failed exception!", e);
                }
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Authentication failed exception!", e);
            }
            LOG.error("Authentication failed exception! " + e.getMessage());
        }
        String data = "Step: " + stepConfig.getOrder() + ", IDP: " + idpName + ", Authenticator:" + authenticatorConfig.getName();
        String initiator = null;
        if (e.getUser() != null) {
            initiator = e.getUser().toFullQualifiedUsername();
        } else if (context.getSubject() != null) {
            initiator = context.getSubject().toFullQualifiedUsername();
        }
        if (!isLegacyAuditLogsDisabled()) {
            audit.warn(String.format(AUDIT_MESSAGE, initiator, "Authenticate", "ApplicationAuthenticationFramework", data, FAILURE));
        }
        handleFailedAuthentication(request, response, context, authenticatorConfig, e.getUser());
    } catch (LogoutFailedException e) {
        throw new FrameworkException(e.getMessage(), e);
    }
    stepConfig.setCompleted(true);
}
Also used : Serializable(java.io.Serializable) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) UserStoreClientException(org.wso2.carbon.user.core.UserStoreClientException) DuplicatedAuthUserException(org.wso2.carbon.identity.application.authentication.framework.exception.DuplicatedAuthUserException) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) LogoutFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) UserSessionException(org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) IdentityErrorMsgContext(org.wso2.carbon.identity.core.model.IdentityErrorMsgContext) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) LocalApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.LocalApplicationAuthenticator) ApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator) InvalidCredentialsException(org.wso2.carbon.identity.application.authentication.framework.exception.InvalidCredentialsException) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) AuthenticatorFlowStatus(org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus) AuthHistory(org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory) AuthenticatedIdPData(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData)

Example 17 with Authenticator

use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator 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 18 with Authenticator

use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.

the class ApplicationInitializer method initEntitlementAuthenticatorRegistry.

private void initEntitlementAuthenticatorRegistry() {
    EntitlementAuthenticatorRegistry entitlementAuthRegistry = EntitlementAuthenticatorRegistry.getInstance();
    if (entitlementAuthRegistry != null) {
        // set authenticators after building auth config
        EntitlementAuthConfigReader configReader = new EntitlementAuthConfigReader();
        List<EntitlementAuthenticationHandler> entitlementAuthenticators = configReader.buildEntitlementAuthenticators();
        if (entitlementAuthenticators != null && !entitlementAuthenticators.isEmpty()) {
            for (EntitlementAuthenticationHandler entitlementAuthenticator : entitlementAuthenticators) {
                entitlementAuthRegistry.setAuthenticator(entitlementAuthenticator);
            }
        } else {
            // initialize default basic auth authenticator & OAuth authenticator and set it in the auth registry.
            BasicAuthHandler basicAuthHandler = new BasicAuthHandler();
            basicAuthHandler.setDefaultPriority();
            entitlementAuthRegistry.setAuthenticator(basicAuthHandler);
        }
    }
}
Also used : EntitlementAuthenticatorRegistry(org.wso2.carbon.identity.entitlement.endpoint.auth.EntitlementAuthenticatorRegistry) EntitlementAuthenticationHandler(org.wso2.carbon.identity.entitlement.endpoint.auth.EntitlementAuthenticationHandler) BasicAuthHandler(org.wso2.carbon.identity.entitlement.endpoint.auth.BasicAuthHandler) EntitlementAuthConfigReader(org.wso2.carbon.identity.entitlement.endpoint.auth.EntitlementAuthConfigReader)

Example 19 with Authenticator

use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.

the class JITProvisioningPostAuthenticationHandler method getLocalClaimValuesOfIDPInNonAttributeSelectionStep.

/**
 * Uses to get local claim values of an authenticated user from an IDP in non attribute selection steps.
 *
 * @param context           Authentication Context.
 * @param stepConfig        Current step configuration.
 * @param externalIdPConfig Identity providers config.
 * @return Mapped federated user values to local claims.
 * @throws PostAuthenticationFailedException Post Authentication failed exception.
 */
private Map<String, String> getLocalClaimValuesOfIDPInNonAttributeSelectionStep(AuthenticationContext context, StepConfig stepConfig, ExternalIdPConfig externalIdPConfig) throws PostAuthenticationFailedException {
    boolean useDefaultIdpDialect = externalIdPConfig.useDefaultLocalIdpDialect();
    ApplicationAuthenticator authenticator = stepConfig.getAuthenticatedAutenticator().getApplicationAuthenticator();
    String idPStandardDialect = authenticator.getClaimDialectURI();
    Map<ClaimMapping, String> extAttrs = stepConfig.getAuthenticatedUser().getUserAttributes();
    Map<String, String> originalExternalAttributeValueMap = FrameworkUtils.getClaimMappings(extAttrs, false);
    Map<String, String> claimMapping = new HashMap<>();
    Map<String, String> localClaimValues = new HashMap<>();
    if (useDefaultIdpDialect && StringUtils.isNotBlank(idPStandardDialect)) {
        try {
            claimMapping = ClaimMetadataHandler.getInstance().getMappingsMapFromOtherDialectToCarbon(idPStandardDialect, originalExternalAttributeValueMap.keySet(), context.getTenantDomain(), true);
        } catch (ClaimMetadataException e) {
            throw new PostAuthenticationFailedException(ErrorMessages.ERROR_WHILE_HANDLING_CLAIM_MAPPINGS.getCode(), ErrorMessages.ERROR_WHILE_HANDLING_CLAIM_MAPPINGS.getMessage(), e);
        }
    } else {
        ClaimMapping[] customClaimMapping = context.getExternalIdP().getClaimMappings();
        for (ClaimMapping externalClaim : customClaimMapping) {
            if (originalExternalAttributeValueMap.containsKey(externalClaim.getRemoteClaim().getClaimUri())) {
                claimMapping.put(externalClaim.getLocalClaim().getClaimUri(), externalClaim.getRemoteClaim().getClaimUri());
            }
        }
    }
    if (claimMapping != null && claimMapping.size() > 0) {
        for (Map.Entry<String, String> entry : claimMapping.entrySet()) {
            if (originalExternalAttributeValueMap.containsKey(entry.getValue()) && originalExternalAttributeValueMap.get(entry.getValue()) != null) {
                localClaimValues.put(entry.getKey(), originalExternalAttributeValueMap.get(entry.getValue()));
            }
        }
    }
    return localClaimValues;
}
Also used : ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) ClaimMetadataException(org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) ApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator) HashMap(java.util.HashMap) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 20 with Authenticator

use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.

the class JITProvisioningPostAuthenticationHandler method handleResponseFlow.

/**
 * This method is used to handle response flow, after going through password provisioning.
 *
 * @param request        HttpServlet request.
 * @param context        Authentication context
 * @return Status of PostAuthnHandler flow.
 * @throws PostAuthenticationFailedException Post Authentication Failed Exception
 */
@SuppressWarnings("unchecked")
private PostAuthnHandlerFlowStatus handleResponseFlow(HttpServletRequest request, AuthenticationContext context) throws PostAuthenticationFailedException {
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    for (Map.Entry<Integer, StepConfig> entry : sequenceConfig.getStepMap().entrySet()) {
        StepConfig stepConfig = entry.getValue();
        AuthenticatorConfig authenticatorConfig = stepConfig.getAuthenticatedAutenticator();
        ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator();
        if (authenticator instanceof FederatedApplicationAuthenticator) {
            String externalIdPConfigName = stepConfig.getAuthenticatedIdP();
            ExternalIdPConfig externalIdPConfig = getExternalIdpConfig(externalIdPConfigName, context);
            context.setExternalIdP(externalIdPConfig);
            if (externalIdPConfig != null && externalIdPConfig.isProvisioningEnabled()) {
                if (log.isDebugEnabled()) {
                    log.debug("JIT provisioning response flow has hit for the IDP " + externalIdPConfigName + " " + "for the user, " + sequenceConfig.getAuthenticatedUser().getLoggableUserId());
                }
                final Map<String, String> localClaimValues;
                Object unfilteredLocalClaimValues = context.getProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIM_VALUES);
                localClaimValues = unfilteredLocalClaimValues == null ? new HashMap<>() : (Map<String, String>) unfilteredLocalClaimValues;
                Map<String, String> combinedLocalClaims = getCombinedClaims(request, localClaimValues, context);
                if (externalIdPConfig.isPasswordProvisioningEnabled()) {
                    combinedLocalClaims.put(FrameworkConstants.PASSWORD, request.getParameter(FrameworkConstants.PASSWORD));
                }
                String username = getUsernameFederatedUser(stepConfig, sequenceConfig, externalIdPConfigName, context, localClaimValues, externalIdPConfig);
                if (context.getProperty(FrameworkConstants.CHANGING_USERNAME_ALLOWED) != null) {
                    username = request.getParameter(FrameworkConstants.USERNAME);
                    try {
                        /*
                            Checks whether the provided user is already existing in the system. If so an exception
                            will be thrown.
                            */
                        UserRealm realm = getUserRealm(context.getTenantDomain());
                        UserStoreManager userStoreManager = getUserStoreManager(context.getExternalIdP().getProvisioningUserStoreId(), realm, username);
                        String sanitizedUserName = UserCoreUtil.removeDomainFromName(MultitenantUtils.getTenantAwareUsername(username));
                        if (userStoreManager.isExistingUser(sanitizedUserName)) {
                            // Logging the error because the thrown exception is handled in the UI.
                            log.error(ErrorMessages.USER_ALREADY_EXISTS_ERROR.getCode() + " - " + ErrorMessages.USER_ALREADY_EXISTS_ERROR.getMessage());
                            handleExceptions(ErrorMessages.USER_ALREADY_EXISTS_ERROR.getMessage(), "provided.username.already.exists", null);
                        }
                    } catch (UserStoreException e) {
                        handleExceptions(ErrorMessages.ERROR_WHILE_CHECKING_USERNAME_EXISTENCE.getMessage(), "error.user.existence", e);
                    }
                }
                callDefaultProvisioningHandler(username, context, externalIdPConfig, combinedLocalClaims, stepConfig);
                handleConsents(request, stepConfig, context.getTenantDomain());
            }
        }
    }
    return SUCCESS_COMPLETED;
}
Also used : AuthenticatorConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig) HashMap(java.util.HashMap) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) ApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator) UserRealm(org.wso2.carbon.user.core.UserRealm) UserStoreException(org.wso2.carbon.user.api.UserStoreException) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) JSONObject(org.json.JSONObject) ExternalIdPConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ExternalIdPConfig) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

FederatedAuthenticatorConfig (org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig)27 IdentityProvider (org.wso2.carbon.identity.application.common.model.IdentityProvider)25 Test (org.testng.annotations.Test)23 IdentityProviderManagementException (org.wso2.carbon.idp.mgt.IdentityProviderManagementException)23 ArrayList (java.util.ArrayList)22 HashMap (java.util.HashMap)22 AuthenticatorConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig)22 ApplicationAuthenticator (org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator)19 StepConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig)19 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)16 FrameworkException (org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException)15 LocalAuthenticatorConfig (org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig)15 ISIntegrationTest (org.wso2.identity.integration.common.utils.ISIntegrationTest)15 IOException (java.io.IOException)12 Map (java.util.Map)12 FederatedApplicationAuthenticator (org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator)12 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)11 RequestPathAuthenticatorConfig (org.wso2.carbon.identity.application.common.model.RequestPathAuthenticatorConfig)11 Property (org.wso2.carbon.identity.application.common.model.Property)10 HttpResponse (org.apache.http.HttpResponse)8