Search in sources :

Example 11 with Authenticator

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

the class IdPManagementDAOTest method testGetIdPByAuthenticatorPropertyValue.

@Test(dataProvider = "getIdPByAuthenticatorPropertyValueData")
public void testGetIdPByAuthenticatorPropertyValue(int tenantId, String idpName, String property, String value, String authenticator, boolean isExist) throws Exception {
    mockStatic(IdentityDatabaseUtil.class);
    try (Connection connection = getConnection(DB_NAME)) {
        when(IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection);
        when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
        when(IdentityDatabaseUtil.getDataSource()).thenReturn(dataSourceMap.get(DB_NAME));
        addTestIdps();
        IdentityProvider idpResult = idPManagementDAO.getIdPByAuthenticatorPropertyValue(connection, property, value, authenticator, tenantId, TENANT_DOMAIN);
        if (isExist) {
            assertEquals(idpResult.getIdentityProviderName(), idpName);
        } else {
            assertNull(idpResult);
        }
    }
}
Also used : Connection(java.sql.Connection) IdentityProvider(org.wso2.carbon.identity.application.common.model.IdentityProvider) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 12 with Authenticator

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

the class ApplicationDAOImpl method updateLocalAndOutboundAuthenticationConfiguration.

/**
 * @param applicationId
 * @param localAndOutboundAuthConfig
 * @param connection
 * @throws SQLException
 * @throws IdentityApplicationManagementException
 */
private void updateLocalAndOutboundAuthenticationConfiguration(int applicationId, LocalAndOutboundAuthenticationConfig localAndOutboundAuthConfig, Connection connection) throws SQLException, IdentityApplicationManagementException {
    int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    if (localAndOutboundAuthConfig == null) {
        // no local or out-bound configuration for this service provider.
        return;
    }
    updateAuthenticationScriptConfiguration(applicationId, localAndOutboundAuthConfig, connection, tenantID);
    PreparedStatement updateAuthTypePrepStmt = null;
    PreparedStatement storeSendAuthListOfIdPsPrepStmt = null;
    try {
        storeSendAuthListOfIdPsPrepStmt = connection.prepareStatement(UPDATE_BASIC_APPINFO_WITH_SEND_AUTH_LIST_OF_IDPS);
        // IS_SEND_LOCAL_SUBJECT_ID=? WHERE TENANT_ID= ? AND ID = ?
        storeSendAuthListOfIdPsPrepStmt.setString(1, localAndOutboundAuthConfig.isAlwaysSendBackAuthenticatedListOfIdPs() ? "1" : "0");
        storeSendAuthListOfIdPsPrepStmt.setInt(2, tenantID);
        storeSendAuthListOfIdPsPrepStmt.setInt(3, applicationId);
        storeSendAuthListOfIdPsPrepStmt.executeUpdate();
    } finally {
        IdentityApplicationManagementUtil.closeStatement(storeSendAuthListOfIdPsPrepStmt);
    }
    PreparedStatement storeUseTenantDomainInLocalSubjectIdStmt = null;
    try {
        storeUseTenantDomainInLocalSubjectIdStmt = connection.prepareStatement(UPDATE_BASIC_APPINFO_WITH_USE_TENANT_DOMAIN_LOCAL_SUBJECT_ID);
        // IS_USE_TENANT_DIMAIN_LOCAL_SUBJECT_ID=? WHERE TENANT_ID= ? AND ID = ?
        storeUseTenantDomainInLocalSubjectIdStmt.setString(1, localAndOutboundAuthConfig.isUseTenantDomainInLocalSubjectIdentifier() ? "1" : "0");
        storeUseTenantDomainInLocalSubjectIdStmt.setInt(2, tenantID);
        storeUseTenantDomainInLocalSubjectIdStmt.setInt(3, applicationId);
        storeUseTenantDomainInLocalSubjectIdStmt.executeUpdate();
    } finally {
        IdentityApplicationManagementUtil.closeStatement(storeUseTenantDomainInLocalSubjectIdStmt);
    }
    PreparedStatement storeUseUserstoreDomainInLocalSubjectIdStmt = null;
    try {
        storeUseUserstoreDomainInLocalSubjectIdStmt = connection.prepareStatement(UPDATE_BASIC_APPINFO_WITH_USE_USERSTORE_DOMAIN_LOCAL_SUBJECT_ID);
        // IS_USE_USERSTORE_DIMAIN_LOCAL_SUBJECT_ID=? WHERE TENANT_ID= ? AND ID = ?
        storeUseUserstoreDomainInLocalSubjectIdStmt.setString(1, localAndOutboundAuthConfig.isUseUserstoreDomainInLocalSubjectIdentifier() ? "1" : "0");
        storeUseUserstoreDomainInLocalSubjectIdStmt.setInt(2, tenantID);
        storeUseUserstoreDomainInLocalSubjectIdStmt.setInt(3, applicationId);
        storeUseUserstoreDomainInLocalSubjectIdStmt.executeUpdate();
    } finally {
        IdentityApplicationManagementUtil.closeStatement(storeUseUserstoreDomainInLocalSubjectIdStmt);
    }
    PreparedStatement enableAuthzStmt = null;
    try {
        enableAuthzStmt = connection.prepareStatement(UPDATE_BASIC_APPINFO_WITH_ENABLE_AUTHORIZATION);
        enableAuthzStmt.setString(1, localAndOutboundAuthConfig.isEnableAuthorization() ? "1" : "0");
        enableAuthzStmt.setInt(2, tenantID);
        enableAuthzStmt.setInt(3, applicationId);
        enableAuthzStmt.executeUpdate();
    } finally {
        IdentityApplicationManagementUtil.closeStatement(enableAuthzStmt);
    }
    PreparedStatement storeSubjectClaimUri = null;
    try {
        storeSubjectClaimUri = connection.prepareStatement(UPDATE_BASIC_APPINFO_WITH_SUBJECT_CLAIM_URI);
        // SUBJECT_CLAIM_URI=? WHERE TENANT_ID= ? AND ID = ?
        storeSubjectClaimUri.setString(1, localAndOutboundAuthConfig.getSubjectClaimUri());
        storeSubjectClaimUri.setInt(2, tenantID);
        storeSubjectClaimUri.setInt(3, applicationId);
        storeSubjectClaimUri.executeUpdate();
    } finally {
        IdentityApplicationManagementUtil.closeStatement(storeSubjectClaimUri);
    }
    AuthenticationStep[] authSteps = localAndOutboundAuthConfig.getAuthenticationSteps();
    if (authSteps == null || authSteps.length == 0) {
        // if no authentication steps defined - it should be the default behavior.
        localAndOutboundAuthConfig.setAuthenticationType(ApplicationConstants.AUTH_TYPE_DEFAULT);
    }
    try {
        if (localAndOutboundAuthConfig.getAuthenticationType() == null) {
            // no authentication type defined - set to default.
            localAndOutboundAuthConfig.setAuthenticationType(ApplicationConstants.AUTH_TYPE_DEFAULT);
        }
        updateAuthTypePrepStmt = connection.prepareStatement(UPDATE_BASIC_APPINFO_WITH_AUTH_TYPE);
        // AUTH_TYPE=? WHERE TENANT_ID= ? AND ID = ?
        updateAuthTypePrepStmt.setString(1, localAndOutboundAuthConfig.getAuthenticationType());
        updateAuthTypePrepStmt.setInt(2, tenantID);
        updateAuthTypePrepStmt.setInt(3, applicationId);
        updateAuthTypePrepStmt.execute();
    } finally {
        IdentityApplicationManagementUtil.closeStatement(updateAuthTypePrepStmt);
    }
    if (authSteps != null && authSteps.length > 0) {
        // we have authentications steps defined.
        PreparedStatement storeStepIDPAuthnPrepStmt = null;
        storeStepIDPAuthnPrepStmt = connection.prepareStatement(STORE_STEP_IDP_AUTH);
        try {
            if (ApplicationConstants.AUTH_TYPE_LOCAL.equalsIgnoreCase(localAndOutboundAuthConfig.getAuthenticationType())) {
                // only one local authenticator.
                if (authSteps.length != 1 || authSteps[0] == null || authSteps[0].getLocalAuthenticatorConfigs() == null || authSteps[0].getLocalAuthenticatorConfigs().length != 1 || (authSteps[0].getFederatedIdentityProviders() != null && authSteps[0].getFederatedIdentityProviders().length >= 1)) {
                    String errorMessage = "Invalid local authentication configuration." + " For local authentication there can only be only one authentication step and" + " only one local authenticator";
                    throw new IdentityApplicationManagementException(errorMessage);
                }
            } else if (ApplicationConstants.AUTH_TYPE_FEDERATED.equalsIgnoreCase(localAndOutboundAuthConfig.getAuthenticationType())) {
                // the corresponding authenticator.
                if (authSteps.length != 1 || authSteps[0] == null || authSteps[0].getFederatedIdentityProviders() == null || authSteps[0].getFederatedIdentityProviders().length != 1 || authSteps[0].getLocalAuthenticatorConfigs().length > 0) {
                    String errorMessage = "Invalid federated authentication configuration." + " For federated authentication there can only be only one authentication step and" + " only one federated authenticator";
                    throw new IdentityApplicationManagementException(errorMessage);
                }
                IdentityProvider fedIdp = authSteps[0].getFederatedIdentityProviders()[0];
                if (fedIdp.getDefaultAuthenticatorConfig() == null || fedIdp.getFederatedAuthenticatorConfigs() == null) {
                    IdentityProviderDAO idpDAO = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
                    String defualtAuthName = idpDAO.getDefaultAuthenticator(fedIdp.getIdentityProviderName());
                    // set the default authenticator.
                    FederatedAuthenticatorConfig defaultAuth = new FederatedAuthenticatorConfig();
                    defaultAuth.setName(defualtAuthName);
                    fedIdp.setDefaultAuthenticatorConfig(defaultAuth);
                    fedIdp.setFederatedAuthenticatorConfigs(new FederatedAuthenticatorConfig[] { defaultAuth });
                }
            }
            // iterating through each step.
            for (AuthenticationStep authStep : authSteps) {
                int stepId = 0;
                IdentityProvider[] federatedIdps = authStep.getFederatedIdentityProviders();
                // provider or a local authenticator.
                if ((federatedIdps == null || federatedIdps.length == 0) && (authStep.getLocalAuthenticatorConfigs() == null || authStep.getLocalAuthenticatorConfigs().length == 0)) {
                    String errorMesssage = "Invalid authentication configuration." + "An authentication step should have at least one federated identity " + "provider or a local authenticator";
                    throw new IdentityApplicationManagementException(errorMesssage);
                }
                // we have valid federated identity providers.
                PreparedStatement storeStepPrepStmtz = null;
                ResultSet result = null;
                try {
                    String dbProductName = connection.getMetaData().getDatabaseProductName();
                    storeStepPrepStmtz = connection.prepareStatement(STORE_STEP_INFO, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "ID") });
                    // TENANT_ID, STEP_ORDER, APP_ID
                    storeStepPrepStmtz.setInt(1, tenantID);
                    storeStepPrepStmtz.setInt(2, authStep.getStepOrder());
                    storeStepPrepStmtz.setInt(3, applicationId);
                    storeStepPrepStmtz.setString(4, authStep.isSubjectStep() ? "1" : "0");
                    storeStepPrepStmtz.setString(5, authStep.isAttributeStep() ? "1" : "0");
                    storeStepPrepStmtz.execute();
                    result = storeStepPrepStmtz.getGeneratedKeys();
                    if (result.next()) {
                        stepId = result.getInt(1);
                    }
                } finally {
                    IdentityApplicationManagementUtil.closeResultSet(result);
                    IdentityApplicationManagementUtil.closeStatement(storeStepPrepStmtz);
                }
                if (authStep.getLocalAuthenticatorConfigs() != null && authStep.getLocalAuthenticatorConfigs().length > 0) {
                    for (LocalAuthenticatorConfig lclAuthenticator : authStep.getLocalAuthenticatorConfigs()) {
                        // set the identity provider name to LOCAL.
                        int authenticatorId = getAuthentictorID(connection, tenantID, ApplicationConstants.LOCAL_IDP_NAME, lclAuthenticator.getName());
                        if (authenticatorId < 0) {
                            authenticatorId = addAuthenticator(connection, tenantID, ApplicationConstants.LOCAL_IDP_NAME, lclAuthenticator.getName(), lclAuthenticator.getDisplayName());
                        }
                        if (authenticatorId > 0) {
                            // ID, TENANT_ID, AUTHENTICATOR_ID
                            storeStepIDPAuthnPrepStmt.setInt(1, stepId);
                            storeStepIDPAuthnPrepStmt.setInt(2, tenantID);
                            storeStepIDPAuthnPrepStmt.setInt(3, authenticatorId);
                            storeStepIDPAuthnPrepStmt.addBatch();
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("Updating Local IdP of Application " + applicationId + " Step Order: " + authStep.getStepOrder() + " IdP: " + ApplicationConstants.LOCAL_IDP + " Authenticator: " + lclAuthenticator.getName());
                        }
                    }
                }
                // we have federated identity providers.
                if (federatedIdps != null && federatedIdps.length > 0) {
                    // iterating through each IDP of the step
                    for (IdentityProvider federatedIdp : federatedIdps) {
                        String idpName = federatedIdp.getIdentityProviderName();
                        // the identity provider name wso2carbon-local-idp is reserved.
                        if (ApplicationConstants.LOCAL_IDP.equalsIgnoreCase(idpName)) {
                            throw new IdentityApplicationManagementException("The federated IdP name cannot be equal to " + ApplicationConstants.LOCAL_IDP);
                        }
                        FederatedAuthenticatorConfig[] authenticators = federatedIdp.getFederatedAuthenticatorConfigs();
                        if (authenticators != null && authenticators.length > 0) {
                            for (FederatedAuthenticatorConfig authenticator : authenticators) {
                                // ID, TENANT_ID, AUTHENTICATOR_ID
                                if (authenticator != null) {
                                    int authenticatorId = getAuthentictorID(connection, tenantID, idpName, authenticator.getName());
                                    if (authenticatorId > 0) {
                                        storeStepIDPAuthnPrepStmt.setInt(1, stepId);
                                        storeStepIDPAuthnPrepStmt.setInt(2, tenantID);
                                        storeStepIDPAuthnPrepStmt.setInt(3, authenticatorId);
                                        storeStepIDPAuthnPrepStmt.addBatch();
                                        if (log.isDebugEnabled()) {
                                            log.debug("Updating Federated IdP of Application " + applicationId + " Step Order: " + authStep.getStepOrder() + " IdP: " + idpName + " Authenticator: " + authenticator);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            storeStepIDPAuthnPrepStmt.executeBatch();
        } finally {
            IdentityApplicationManagementUtil.closeStatement(storeStepIDPAuthnPrepStmt);
        }
    }
}
Also used : FederatedAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) LocalAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig) AuthenticationStep(org.wso2.carbon.identity.application.common.model.AuthenticationStep) PreparedStatement(java.sql.PreparedStatement) NamedPreparedStatement(org.wso2.carbon.database.utils.jdbc.NamedPreparedStatement) IdentityProvider(org.wso2.carbon.identity.application.common.model.IdentityProvider) ResultSet(java.sql.ResultSet) IdentityProviderDAO(org.wso2.carbon.identity.application.mgt.dao.IdentityProviderDAO)

Example 13 with Authenticator

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

the class ApplicationBean method updateOutBoundAuthenticationConfig.

/**
 * @param request
 */
public void updateOutBoundAuthenticationConfig(HttpServletRequest request) {
    String[] authSteps = request.getParameterValues("auth_step");
    if (authSteps != null && authSteps.length > 0) {
        List<AuthenticationStep> authStepList = new ArrayList<AuthenticationStep>();
        for (String authstep : authSteps) {
            AuthenticationStep authStep = new AuthenticationStep();
            authStep.setStepOrder(Integer.parseInt(authstep));
            boolean isSubjectStep = request.getParameter("subject_step_" + authstep) != null && "on".equals(request.getParameter("subject_step_" + authstep)) ? true : false;
            authStep.setSubjectStep(isSubjectStep);
            boolean isAttributeStep = request.getParameter("attribute_step_" + authstep) != null && "on".equals(request.getParameter("attribute_step_" + authstep)) ? true : false;
            authStep.setAttributeStep(isAttributeStep);
            String[] localAuthenticatorNames = request.getParameterValues("step_" + authstep + "_local_auth");
            if (localAuthenticatorNames != null && localAuthenticatorNames.length > 0) {
                List<LocalAuthenticatorConfig> localAuthList = new ArrayList<LocalAuthenticatorConfig>();
                for (String name : localAuthenticatorNames) {
                    if (name != null) {
                        LocalAuthenticatorConfig localAuth = new LocalAuthenticatorConfig();
                        localAuth.setName(name);
                        if (localAuthenticatorConfigs != null) {
                            for (LocalAuthenticatorConfig config : localAuthenticatorConfigs) {
                                if (config.getName().equals(name)) {
                                    localAuth.setDisplayName(config.getDisplayName());
                                    break;
                                }
                            }
                        }
                        localAuthList.add(localAuth);
                    }
                }
                if (localAuthList != null && !localAuthList.isEmpty()) {
                    authStep.setLocalAuthenticatorConfigs(localAuthList.toArray(new LocalAuthenticatorConfig[localAuthList.size()]));
                }
            }
            String[] federatedIdpNames = request.getParameterValues("step_" + authstep + "_fed_auth");
            if (federatedIdpNames != null && federatedIdpNames.length > 0) {
                List<IdentityProvider> fedIdpList = new ArrayList<>();
                for (String name : federatedIdpNames) {
                    if (StringUtils.isNotBlank(name)) {
                        IdentityProvider idp = new IdentityProvider();
                        idp.setIdentityProviderName(name);
                        IdentityProvider referringIdP = federatedIdentityProvidersMap.get(name);
                        String authenticatorName = request.getParameter("step_" + authstep + "_idp_" + name + "_fed_authenticator");
                        if (StringUtils.isNotBlank(authenticatorName)) {
                            String authenticatorDisplayName = null;
                            for (FederatedAuthenticatorConfig config : referringIdP.getFederatedAuthenticatorConfigs()) {
                                if (authenticatorName.equals(config.getName())) {
                                    authenticatorDisplayName = config.getDisplayName();
                                    break;
                                }
                            }
                            FederatedAuthenticatorConfig authenticator = new FederatedAuthenticatorConfig();
                            authenticator.setName(authenticatorName);
                            authenticator.setDisplayName(authenticatorDisplayName);
                            idp.setDefaultAuthenticatorConfig(authenticator);
                            idp.setFederatedAuthenticatorConfigs(new FederatedAuthenticatorConfig[] { authenticator });
                            fedIdpList.add(idp);
                        }
                    }
                }
                if (fedIdpList != null && !fedIdpList.isEmpty()) {
                    authStep.setFederatedIdentityProviders(fedIdpList.toArray(new IdentityProvider[fedIdpList.size()]));
                }
            }
            if ((authStep.getFederatedIdentityProviders() != null && authStep.getFederatedIdentityProviders().length > 0) || (authStep.getLocalAuthenticatorConfigs() != null && authStep.getLocalAuthenticatorConfigs().length > 0)) {
                authStepList.add(authStep);
            }
        }
        if (serviceProvider.getLocalAndOutBoundAuthenticationConfig() == null) {
            serviceProvider.setLocalAndOutBoundAuthenticationConfig(new LocalAndOutboundAuthenticationConfig());
        }
        if (CollectionUtils.isNotEmpty(authStepList)) {
            LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig = serviceProvider.getLocalAndOutBoundAuthenticationConfig();
            localAndOutboundAuthenticationConfig.setAuthenticationSteps(authStepList.toArray(new AuthenticationStep[authStepList.size()]));
        }
    }
}
Also used : LocalAndOutboundAuthenticationConfig(org.wso2.carbon.identity.application.common.model.xsd.LocalAndOutboundAuthenticationConfig) FederatedAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.xsd.FederatedAuthenticatorConfig) ArrayList(java.util.ArrayList) LocalAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.xsd.LocalAuthenticatorConfig) AuthenticationStep(org.wso2.carbon.identity.application.common.model.xsd.AuthenticationStep) IdentityProvider(org.wso2.carbon.identity.application.common.model.xsd.IdentityProvider)

Example 14 with Authenticator

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

the class FrameworkServiceComponent method setAuthenticator.

@Reference(name = "application.authenticator", service = ApplicationAuthenticator.class, cardinality = ReferenceCardinality.AT_LEAST_ONE, policy = ReferencePolicy.DYNAMIC, unbind = "unsetAuthenticator")
protected void setAuthenticator(ApplicationAuthenticator authenticator) {
    FrameworkServiceDataHolder.getInstance().getAuthenticators().add(authenticator);
    Property[] configProperties = null;
    List<Property> configurationProperties = authenticator.getConfigurationProperties();
    if (configurationProperties == null) {
        configurationProperties = new ArrayList<>();
    }
    if (authenticator instanceof AuthenticationFlowHandler) {
        Property handlerProperty = new Property();
        handlerProperty.setName(IS_HANDLER);
        handlerProperty.setValue(TRUE);
        configurationProperties.add(handlerProperty);
    }
    if (!configurationProperties.isEmpty()) {
        configProperties = configurationProperties.toArray(new Property[0]);
    }
    if ((authenticator instanceof LocalApplicationAuthenticator) || (authenticator instanceof AuthenticationFlowHandler)) {
        LocalAuthenticatorConfig localAuthenticatorConfig = new LocalAuthenticatorConfig();
        localAuthenticatorConfig.setName(authenticator.getName());
        localAuthenticatorConfig.setProperties(configProperties);
        localAuthenticatorConfig.setDisplayName(authenticator.getFriendlyName());
        localAuthenticatorConfig.setTags(authenticator.getTags());
        AuthenticatorConfig fileBasedConfig = getAuthenticatorConfig(authenticator.getName());
        localAuthenticatorConfig.setEnabled(fileBasedConfig.isEnabled());
        ApplicationAuthenticatorService.getInstance().addLocalAuthenticator(localAuthenticatorConfig);
    } else if (authenticator instanceof FederatedApplicationAuthenticator) {
        FederatedAuthenticatorConfig federatedAuthenticatorConfig = new FederatedAuthenticatorConfig();
        federatedAuthenticatorConfig.setName(authenticator.getName());
        federatedAuthenticatorConfig.setProperties(configProperties);
        federatedAuthenticatorConfig.setDisplayName(authenticator.getFriendlyName());
        federatedAuthenticatorConfig.setTags(authenticator.getTags());
        ApplicationAuthenticatorService.getInstance().addFederatedAuthenticator(federatedAuthenticatorConfig);
    } else if (authenticator instanceof RequestPathApplicationAuthenticator) {
        RequestPathAuthenticatorConfig reqPathAuthenticatorConfig = new RequestPathAuthenticatorConfig();
        reqPathAuthenticatorConfig.setName(authenticator.getName());
        reqPathAuthenticatorConfig.setProperties(configProperties);
        reqPathAuthenticatorConfig.setDisplayName(authenticator.getFriendlyName());
        reqPathAuthenticatorConfig.setTags(authenticator.getTags());
        AuthenticatorConfig fileBasedConfig = getAuthenticatorConfig(authenticator.getName());
        reqPathAuthenticatorConfig.setEnabled(fileBasedConfig.isEnabled());
        ApplicationAuthenticatorService.getInstance().addRequestPathAuthenticator(reqPathAuthenticatorConfig);
    }
    if (log.isDebugEnabled()) {
        log.debug("Added application authenticator : " + authenticator.getName());
    }
}
Also used : RequestPathAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.RequestPathAuthenticatorConfig) LocalAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig) AuthenticatorConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig) FederatedAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig) FederatedAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig) RequestPathApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.RequestPathApplicationAuthenticator) AuthenticationFlowHandler(org.wso2.carbon.identity.application.authentication.framework.AuthenticationFlowHandler) LocalAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig) RequestPathAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.RequestPathAuthenticatorConfig) Property(org.wso2.carbon.identity.application.common.model.Property) LocalApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.LocalApplicationAuthenticator) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) Reference(org.osgi.service.component.annotations.Reference)

Example 15 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 handle.

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws FrameworkException {
    if (context.getAnalyticsData(FrameworkConstants.AnalyticsData.CURRENT_AUTHENTICATOR_START_TIME) == null) {
        context.setAnalyticsData(FrameworkConstants.AnalyticsData.CURRENT_AUTHENTICATOR_START_TIME, System.currentTimeMillis());
    }
    StepConfig stepConfig = context.getSequenceConfig().getStepMap().get(context.getCurrentStep());
    List<AuthenticatorConfig> authConfigList = stepConfig.getAuthenticatorList();
    String authenticatorNames = FrameworkUtils.getAuthenticatorIdPMappingString(authConfigList);
    String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL();
    String fidp = request.getParameter(FrameworkConstants.RequestParams.FEDERATED_IDP);
    Map<String, AuthenticatedIdPData> authenticatedIdPs = context.getCurrentAuthenticatedIdPs();
    // NOTE : currentAuthenticatedIdPs (if not null) always contains the previousAuthenticatedIdPs
    if (MapUtils.isEmpty(authenticatedIdPs)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No current authenticated IDPs in the authentication context. " + "Continuing with the previous authenticated IDPs");
        }
        authenticatedIdPs = context.getPreviousAuthenticatedIdPs();
    }
    if (LOG.isDebugEnabled()) {
        if (MapUtils.isEmpty(authenticatedIdPs)) {
            LOG.debug("No previous authenticated IDPs found in the authentication context.");
        } else {
            LOG.debug(String.format("Found authenticated IdPs. Count: %d", authenticatedIdPs.size()));
        }
    }
    if (context.isPassiveAuthenticate() && MapUtils.isNotEmpty(context.getAuthenticatedIdPsOfApp())) {
        authenticatedIdPs = context.getAuthenticatedIdPsOfApp();
    }
    Map<String, AuthenticatorConfig> authenticatedStepIdps = FrameworkUtils.getAuthenticatedStepIdPs(stepConfig, authenticatedIdPs);
    // check passive authentication
    if (context.isPassiveAuthenticate()) {
        if (authenticatedStepIdps.isEmpty()) {
            context.setRequestAuthenticated(false);
        } else {
            String authenticatedIdP = authenticatedStepIdps.entrySet().iterator().next().getKey();
            AuthenticatedIdPData authenticatedIdPData = authenticatedIdPs.get(authenticatedIdP);
            populateStepConfigWithAuthenticationDetails(stepConfig, authenticatedIdPData, authenticatedStepIdps.get(authenticatedIdP));
            request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.SUCCESS_COMPLETED);
        }
        stepConfig.setCompleted(true);
        return;
    } else {
        long authTime = 0;
        String maxAgeParam = request.getParameter(FrameworkConstants.RequestParams.MAX_AGE);
        if (StringUtils.isNotBlank(maxAgeParam) && StringUtils.isNotBlank(context.getSessionIdentifier())) {
            String loginTenantDomain = context.getLoginTenantDomain();
            long maxAge = Long.parseLong((maxAgeParam));
            if (FrameworkUtils.getSessionContextFromCache(context.getSessionIdentifier(), loginTenantDomain).getProperty(FrameworkConstants.UPDATED_TIMESTAMP) != null) {
                authTime = Long.parseLong(FrameworkUtils.getSessionContextFromCache(context.getSessionIdentifier(), loginTenantDomain).getProperty(FrameworkConstants.UPDATED_TIMESTAMP).toString());
            } else {
                authTime = Long.parseLong(FrameworkUtils.getSessionContextFromCache(context.getSessionIdentifier(), loginTenantDomain).getProperty(FrameworkConstants.CREATED_TIMESTAMP).toString());
            }
            long currentTime = System.currentTimeMillis();
            if (maxAge < (currentTime - authTime) / 1000) {
                context.setForceAuthenticate(true);
            } else {
                context.setPreviousAuthTime(true);
            }
        }
    }
    if (request.getParameter(FrameworkConstants.RequestParams.USER_ABORT) != null && Boolean.parseBoolean(request.getParameter(FrameworkConstants.RequestParams.USER_ABORT))) {
        request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.USER_ABORT);
        stepConfig.setCompleted(true);
        return;
    }
    // if Request has fidp param and if this is the first step
    if (fidp != null && stepConfig.getOrder() == 1) {
        handleHomeRealmDiscovery(request, response, context);
        return;
    } else if (context.isReturning()) {
        // if this is a request from the multi-option page
        if (request.getParameter(FrameworkConstants.RequestParams.AUTHENTICATOR) != null && !request.getParameter(FrameworkConstants.RequestParams.AUTHENTICATOR).isEmpty()) {
            handleRequestFromLoginPage(request, response, context);
            return;
        } else {
            // if this is a response from external parties (e.g. federated IdPs)
            handleResponse(request, response, context);
            return;
        }
    } else if (ConfigurationFacade.getInstance().isDumbMode() && authenticatedIdPs.isEmpty()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing in Dumb mode");
        }
        try {
            request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
            response.sendRedirect(loginPage + ("?" + context.getContextIdIncludedQueryParams()) + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + "&hrd=true");
        } catch (IOException e) {
            throw new FrameworkException(e.getMessage(), e);
        }
    } else {
        if (!(context.isForceAuthenticate() || stepConfig.isForced()) && !authenticatedStepIdps.isEmpty()) {
            Map.Entry<String, AuthenticatorConfig> entry = authenticatedStepIdps.entrySet().iterator().next();
            String idp = entry.getKey();
            AuthenticatorConfig authenticatorConfig = entry.getValue();
            if (context.isReAuthenticate()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Re-authenticating with " + idp + " IdP");
                }
                try {
                    context.setExternalIdP(ConfigurationFacade.getInstance().getIdPConfigByName(idp, context.getTenantDomain()));
                } catch (IdentityProviderManagementException e) {
                    LOG.error("Exception while getting IdP by name", e);
                }
                doAuthentication(request, response, context, authenticatorConfig);
                return;
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Already authenticated. Skipping the step");
                }
                // skip the step if this is a normal request
                AuthenticatedIdPData authenticatedIdPData = authenticatedIdPs.get(idp);
                populateStepConfigWithAuthenticationDetails(stepConfig, authenticatedIdPData, authenticatedStepIdps.get(idp));
                context.getCurrentAuthenticatedIdPs().put(idp, authenticatedIdPData);
                stepConfig.setCompleted(true);
                request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.SUCCESS_COMPLETED);
                return;
            }
        } else {
            // Find if step contains only a single authenticator with a single
            // IdP. If yes, don't send to the multi-option page. Call directly.
            boolean sendToPage = false;
            boolean isAuthFlowHandlerOrBasicAuthInMultiOptionStep = false;
            AuthenticatorConfig authenticatorConfig = null;
            // Are there multiple authenticators?
            if (authConfigList.size() > 1) {
                sendToPage = true;
                // redirecting to the multi option page.
                for (AuthenticatorConfig config : authConfigList) {
                    if ((config.getApplicationAuthenticator() instanceof AuthenticationFlowHandler) || (config.getApplicationAuthenticator() instanceof LocalApplicationAuthenticator && (BASIC_AUTH_MECHANISM).equalsIgnoreCase(config.getApplicationAuthenticator().getAuthMechanism()))) {
                        authenticatorConfig = config;
                        isAuthFlowHandlerOrBasicAuthInMultiOptionStep = true;
                        sendToPage = false;
                        break;
                    }
                }
            } else {
                // Are there multiple IdPs in the single authenticator?
                authenticatorConfig = authConfigList.get(0);
                if (authenticatorConfig.getIdpNames().size() > 1) {
                    sendToPage = true;
                }
            }
            if (!sendToPage) {
                // call directly
                if (!authenticatorConfig.getIdpNames().isEmpty()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Step contains only a single IdP. Going to call it directly");
                    }
                    // set the IdP to be called in the context
                    try {
                        context.setExternalIdP(ConfigurationFacade.getInstance().getIdPConfigByName(authenticatorConfig.getIdpNames().get(0), context.getTenantDomain()));
                    } catch (IdentityProviderManagementException e) {
                        LOG.error("Exception while getting IdP by name", e);
                    }
                }
                doAuthentication(request, response, context, authenticatorConfig);
                /* If an authentication flow handler is redirected with incomplete status,
                    it will redirect to multi option page, as multi-option is available */
                if ((request.getAttribute(FrameworkConstants.RequestParams.FLOW_STATUS)) == AuthenticatorFlowStatus.INCOMPLETE && isAuthFlowHandlerOrBasicAuthInMultiOptionStep) {
                    sendToMultiOptionPage(stepConfig, request, context, response, authenticatorNames);
                }
                return;
            } else {
                // else send to the multi option page.
                sendToMultiOptionPage(stepConfig, request, context, response, authenticatorNames);
                return;
            }
        }
    }
}
Also used : AuthenticatorConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) IOException(java.io.IOException) LocalApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.LocalApplicationAuthenticator) AuthenticationFlowHandler(org.wso2.carbon.identity.application.authentication.framework.AuthenticationFlowHandler) Map(java.util.Map) HashMap(java.util.HashMap) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException) AuthenticatedIdPData(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData)

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