Search in sources :

Example 1 with StringUtils.isNotBlank

use of org.apache.commons.lang3.StringUtils.isNotBlank in project cas by apereo.

the class AbstractPrincipalAttributesRepository method getAttributes.

@Override
public Map<String, Object> getAttributes(final Principal p) {
    final Map<String, Object> cachedAttributes = getPrincipalAttributes(p);
    if (cachedAttributes != null && !cachedAttributes.isEmpty()) {
        LOGGER.debug("Found [{}] cached attributes for principal [{}] that are [{}]", cachedAttributes.size(), p.getId(), cachedAttributes);
        return cachedAttributes;
    }
    if (getAttributeRepository() == null) {
        LOGGER.debug("No attribute repository is defined for [{}]. Returning default principal attributes for [{}]", getClass().getName(), p.getId());
        return cachedAttributes;
    }
    final Map<String, List<Object>> sourceAttributes = retrievePersonAttributesToPrincipalAttributes(p.getId());
    LOGGER.debug("Found [{}] attributes for principal [[{}]] from the attribute repository.", sourceAttributes.size(), p.getId());
    if (this.mergingStrategy == null || this.mergingStrategy.getAttributeMerger() == null) {
        LOGGER.debug("No merging strategy found, so attributes retrieved from the repository will be used instead.");
        return convertAttributesToPrincipalAttributesAndCache(p, sourceAttributes);
    }
    final Map<String, List<Object>> principalAttributes = convertPrincipalAttributesToPersonAttributes(p);
    LOGGER.debug("Merging current principal attributes with that of the repository via strategy [{}]", this.mergingStrategy.getClass().getSimpleName());
    try {
        final Map<String, List<Object>> mergedAttributes = this.mergingStrategy.getAttributeMerger().mergeAttributes(principalAttributes, sourceAttributes);
        return convertAttributesToPrincipalAttributesAndCache(p, mergedAttributes);
    } catch (final Exception e) {
        final StringBuilder builder = new StringBuilder();
        builder.append(e.getClass().getName().concat("-"));
        if (StringUtils.isNotBlank(e.getMessage())) {
            builder.append(e.getMessage());
        }
        LOGGER.error("The merging strategy [{}] for [{}] has failed to produce principal attributes because: [{}]. " + "This usually is indicative of a bug and/or configuration mismatch. CAS will skip the merging process " + "and will return the original collection of principal attributes [{}]", this.mergingStrategy, p.getId(), builder.toString(), principalAttributes);
        return convertAttributesToPrincipalAttributesAndCache(p, principalAttributes);
    }
}
Also used : ToStringBuilder(org.apache.commons.lang3.builder.ToStringBuilder) List(java.util.List)

Example 2 with StringUtils.isNotBlank

use of org.apache.commons.lang3.StringUtils.isNotBlank in project cas by apereo.

the class LogoutAction method doInternalExecute.

@Override
protected Event doInternalExecute(final HttpServletRequest request, final HttpServletResponse response, final RequestContext context) throws Exception {
    boolean needFrontSlo = false;
    final List<LogoutRequest> logoutRequests = WebUtils.getLogoutRequests(context);
    if (logoutRequests != null) {
        // if some logout request must still be attempted
        needFrontSlo = logoutRequests.stream().anyMatch(logoutRequest -> logoutRequest.getStatus() == LogoutRequestStatus.NOT_ATTEMPTED);
    }
    final String paramName = StringUtils.defaultIfEmpty(logoutProperties.getRedirectParameter(), CasProtocolConstants.PARAMETER_SERVICE);
    LOGGER.debug("Using parameter name [{}] to detect destination service, if any", paramName);
    final String service = request.getParameter(paramName);
    LOGGER.debug("Located target service [{}] for redirection after logout", paramName);
    if (logoutProperties.isFollowServiceRedirects() && StringUtils.isNotBlank(service)) {
        final Service webAppService = webApplicationServiceFactory.createService(service);
        final RegisteredService rService = this.servicesManager.findServiceBy(webAppService);
        if (rService != null && rService.getAccessStrategy().isServiceAccessAllowed()) {
            LOGGER.debug("Redirecting to service [{}]", service);
            WebUtils.putLogoutRedirectUrl(context, service);
        } else {
            LOGGER.warn("Cannot redirect to [{}] given the service is unauthorized to use CAS. " + "Ensure the service is registered with CAS and is enabled to allowed access", service);
        }
    } else {
        LOGGER.debug("No target service is located for redirection after logout, or CAS is not allowed to follow redirects after logout");
    }
    // there are some front services to logout, perform front SLO
    if (needFrontSlo) {
        LOGGER.debug("Proceeding forward with front-channel single logout");
        return new Event(this, FRONT_EVENT);
    }
    LOGGER.debug("Moving forward to finish the logout process");
    return new Event(this, FINISH_EVENT);
}
Also used : CasProtocolConstants(org.apereo.cas.CasProtocolConstants) LogoutRequest(org.apereo.cas.logout.LogoutRequest) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) HttpServletResponse(javax.servlet.http.HttpServletResponse) LogoutRequestStatus(org.apereo.cas.logout.LogoutRequestStatus) LogoutProperties(org.apereo.cas.configuration.model.core.logout.LogoutProperties) StringUtils(org.apache.commons.lang3.StringUtils) RequestContext(org.springframework.webflow.execution.RequestContext) RegisteredService(org.apereo.cas.services.RegisteredService) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) HttpServletRequest(javax.servlet.http.HttpServletRequest) List(java.util.List) Service(org.apereo.cas.authentication.principal.Service) WebUtils(org.apereo.cas.web.support.WebUtils) ServiceFactory(org.apereo.cas.authentication.principal.ServiceFactory) Event(org.springframework.webflow.execution.Event) ServicesManager(org.apereo.cas.services.ServicesManager) RegisteredService(org.apereo.cas.services.RegisteredService) RegisteredService(org.apereo.cas.services.RegisteredService) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) Service(org.apereo.cas.authentication.principal.Service) Event(org.springframework.webflow.execution.Event) LogoutRequest(org.apereo.cas.logout.LogoutRequest)

Example 3 with StringUtils.isNotBlank

use of org.apache.commons.lang3.StringUtils.isNotBlank in project cas by apereo.

the class DuoSecurityAuthenticationEventExecutionPlanConfiguration method duoMultifactorAuthenticationProvider.

@Bean
@RefreshScope
public VariegatedMultifactorAuthenticationProvider duoMultifactorAuthenticationProvider() {
    final DefaultVariegatedMultifactorAuthenticationProvider provider = new DefaultVariegatedMultifactorAuthenticationProvider();
    casProperties.getAuthn().getMfa().getDuo().stream().filter(duo -> StringUtils.isNotBlank(duo.getDuoApiHost()) && StringUtils.isNotBlank(duo.getDuoIntegrationKey()) && StringUtils.isNotBlank(duo.getDuoSecretKey()) && StringUtils.isNotBlank(duo.getDuoApplicationKey())).forEach(duo -> {
        final BasicDuoAuthenticationService s = new BasicDuoAuthenticationService(duo, httpClient);
        final DefaultDuoMultifactorAuthenticationProvider pWeb = new DefaultDuoMultifactorAuthenticationProvider(s);
        pWeb.setGlobalFailureMode(casProperties.getAuthn().getMfa().getGlobalFailureMode());
        pWeb.setBypassEvaluator(new DefaultMultifactorAuthenticationProviderBypass(duo.getBypass()));
        pWeb.setOrder(duo.getRank());
        pWeb.setId(duo.getId());
        provider.addProvider(pWeb);
    });
    if (provider.getProviders().isEmpty()) {
        throw new IllegalArgumentException("At least one Duo instance must be defined");
    }
    return provider;
}
Also used : PrepareDuoWebLoginFormAction(org.apereo.cas.adaptors.duo.web.flow.action.PrepareDuoWebLoginFormAction) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) DefaultVariegatedMultifactorAuthenticationProvider(org.apereo.cas.services.DefaultVariegatedMultifactorAuthenticationProvider) AuthenticationMetaDataPopulator(org.apereo.cas.authentication.AuthenticationMetaDataPopulator) Ordered(org.springframework.core.Ordered) HttpClient(org.apereo.cas.util.http.HttpClient) DuoMultifactorWebflowConfigurer(org.apereo.cas.adaptors.duo.web.flow.config.DuoMultifactorWebflowConfigurer) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) DefaultDuoMultifactorAuthenticationProvider(org.apereo.cas.adaptors.duo.authn.DefaultDuoMultifactorAuthenticationProvider) FlowBuilderServices(org.springframework.webflow.engine.builder.support.FlowBuilderServices) StringUtils(org.apache.commons.lang3.StringUtils) AuthenticationEventExecutionPlan(org.apereo.cas.authentication.AuthenticationEventExecutionPlan) RefreshScope(org.springframework.cloud.context.config.annotation.RefreshScope) AuthenticationHandler(org.apereo.cas.authentication.AuthenticationHandler) PrincipalFactory(org.apereo.cas.authentication.principal.PrincipalFactory) MultifactorAuthenticationProperties(org.apereo.cas.configuration.model.support.mfa.MultifactorAuthenticationProperties) BeanCreationException(org.springframework.beans.factory.BeanCreationException) EnableConfigurationProperties(org.springframework.boot.context.properties.EnableConfigurationProperties) BasicDuoAuthenticationService(org.apereo.cas.adaptors.duo.authn.BasicDuoAuthenticationService) Qualifier(org.springframework.beans.factory.annotation.Qualifier) DuoAuthenticationHandler(org.apereo.cas.adaptors.duo.authn.DuoAuthenticationHandler) VariegatedMultifactorAuthenticationProvider(org.apereo.cas.services.VariegatedMultifactorAuthenticationProvider) ServicesManager(org.apereo.cas.services.ServicesManager) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Order(org.springframework.core.annotation.Order) AuthenticationContextAttributeMetaDataPopulator(org.apereo.cas.authentication.metadata.AuthenticationContextAttributeMetaDataPopulator) Logger(org.slf4j.Logger) FlowDefinitionRegistry(org.springframework.webflow.definition.registry.FlowDefinitionRegistry) AutoConfigureOrder(org.springframework.boot.autoconfigure.AutoConfigureOrder) Action(org.springframework.webflow.execution.Action) AuthenticationEventExecutionPlanConfigurer(org.apereo.cas.config.support.authentication.AuthenticationEventExecutionPlanConfigurer) DefaultMultifactorAuthenticationProviderBypass(org.apereo.cas.services.DefaultMultifactorAuthenticationProviderBypass) Configuration(org.springframework.context.annotation.Configuration) List(java.util.List) CasWebflowConfigurer(org.apereo.cas.web.flow.CasWebflowConfigurer) Bean(org.springframework.context.annotation.Bean) DefaultPrincipalFactory(org.apereo.cas.authentication.principal.DefaultPrincipalFactory) BasicDuoAuthenticationService(org.apereo.cas.adaptors.duo.authn.BasicDuoAuthenticationService) DefaultMultifactorAuthenticationProviderBypass(org.apereo.cas.services.DefaultMultifactorAuthenticationProviderBypass) DefaultDuoMultifactorAuthenticationProvider(org.apereo.cas.adaptors.duo.authn.DefaultDuoMultifactorAuthenticationProvider) DefaultVariegatedMultifactorAuthenticationProvider(org.apereo.cas.services.DefaultVariegatedMultifactorAuthenticationProvider) RefreshScope(org.springframework.cloud.context.config.annotation.RefreshScope) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Bean(org.springframework.context.annotation.Bean)

Example 4 with StringUtils.isNotBlank

use of org.apache.commons.lang3.StringUtils.isNotBlank in project DataX by alibaba.

the class SecretUtil method getPrivateKeyMap.

private static synchronized Map<String, Triple<String, String, String>> getPrivateKeyMap() {
    if (versionKeyMap == null) {
        versionKeyMap = new HashMap<String, Triple<String, String, String>>();
        Properties properties = SecretUtil.getSecurityProperties();
        String[] serviceUsernames = new String[] { CoreConstant.LAST_SERVICE_USERNAME, CoreConstant.CURRENT_SERVICE_USERNAME };
        String[] servicePasswords = new String[] { CoreConstant.LAST_SERVICE_PASSWORD, CoreConstant.CURRENT_SERVICE_PASSWORD };
        for (int i = 0; i < serviceUsernames.length; i++) {
            String serviceUsername = properties.getProperty(serviceUsernames[i]);
            if (StringUtils.isNotBlank(serviceUsername)) {
                String servicePassword = properties.getProperty(servicePasswords[i]);
                if (StringUtils.isNotBlank(servicePassword)) {
                    versionKeyMap.put(serviceUsername, ImmutableTriple.of(servicePassword, SecretUtil.KEY_ALGORITHM_3DES, servicePassword));
                } else {
                    throw DataXException.asDataXException(FrameworkErrorCode.SECRET_ERROR, String.format("DataX配置要求加解密,但配置的密钥版本[%s]存在密钥为空的情况", serviceUsername));
                }
            }
        }
        String[] keyVersions = new String[] { CoreConstant.LAST_KEYVERSION, CoreConstant.CURRENT_KEYVERSION };
        String[] privateKeys = new String[] { CoreConstant.LAST_PRIVATEKEY, CoreConstant.CURRENT_PRIVATEKEY };
        String[] publicKeys = new String[] { CoreConstant.LAST_PUBLICKEY, CoreConstant.CURRENT_PUBLICKEY };
        for (int i = 0; i < keyVersions.length; i++) {
            String keyVersion = properties.getProperty(keyVersions[i]);
            if (StringUtils.isNotBlank(keyVersion)) {
                String privateKey = properties.getProperty(privateKeys[i]);
                String publicKey = properties.getProperty(publicKeys[i]);
                if (StringUtils.isNotBlank(privateKey) && StringUtils.isNotBlank(publicKey)) {
                    versionKeyMap.put(keyVersion, ImmutableTriple.of(privateKey, SecretUtil.KEY_ALGORITHM_RSA, publicKey));
                } else {
                    throw DataXException.asDataXException(FrameworkErrorCode.SECRET_ERROR, String.format("DataX配置要求加解密,但配置的公私钥对存在为空的情况,版本[%s]", keyVersion));
                }
            }
        }
    }
    if (versionKeyMap.size() <= 0) {
        throw DataXException.asDataXException(FrameworkErrorCode.SECRET_ERROR, "DataX配置要求加解密,但无法找到加解密配置");
    }
    return versionKeyMap;
}
Also used : Triple(org.apache.commons.lang3.tuple.Triple) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) Properties(java.util.Properties)

Example 5 with StringUtils.isNotBlank

use of org.apache.commons.lang3.StringUtils.isNotBlank in project DataX by alibaba.

the class SingleTableSplitUtil method genSplitSqlForOracle.

/**
     * support Number and String split
     * */
public static List<String> genSplitSqlForOracle(String splitPK, String table, String where, Configuration configuration, int adviceNum) {
    if (adviceNum < 1) {
        throw new IllegalArgumentException(String.format("切分份数不能小于1. 此处:adviceNum=[%s].", adviceNum));
    } else if (adviceNum == 1) {
        return null;
    }
    String whereSql = String.format("%s IS NOT NULL", splitPK);
    if (StringUtils.isNotBlank(where)) {
        whereSql = String.format(" WHERE (%s) AND (%s) ", whereSql, where);
    } else {
        whereSql = String.format(" WHERE (%s) ", whereSql);
    }
    Double percentage = configuration.getDouble(Key.SAMPLE_PERCENTAGE, 0.1);
    String sampleSqlTemplate = "SELECT * FROM ( SELECT %s FROM %s SAMPLE (%s) %s ORDER BY DBMS_RANDOM.VALUE) WHERE ROWNUM <= %s ORDER by %s ASC";
    String splitSql = String.format(sampleSqlTemplate, splitPK, table, percentage, whereSql, adviceNum, splitPK);
    int fetchSize = configuration.getInt(Constant.FETCH_SIZE, 32);
    String jdbcURL = configuration.getString(Key.JDBC_URL);
    String username = configuration.getString(Key.USERNAME);
    String password = configuration.getString(Key.PASSWORD);
    Connection conn = DBUtil.getConnection(DATABASE_TYPE, jdbcURL, username, password);
    LOG.info("split pk [sql={}] is running... ", splitSql);
    ResultSet rs = null;
    List<Pair<Object, Integer>> splitedRange = new ArrayList<Pair<Object, Integer>>();
    try {
        try {
            rs = DBUtil.query(conn, splitSql, fetchSize);
        } catch (Exception e) {
            throw RdbmsException.asQueryException(DATABASE_TYPE, e, splitSql, table, username);
        }
        if (configuration != null) {
            configuration.set(Constant.PK_TYPE, Constant.PK_TYPE_MONTECARLO);
        }
        ResultSetMetaData rsMetaData = rs.getMetaData();
        while (DBUtil.asyncResultSetNext(rs)) {
            ImmutablePair<Object, Integer> eachPoint = new ImmutablePair<Object, Integer>(rs.getObject(1), rsMetaData.getColumnType(1));
            splitedRange.add(eachPoint);
        }
    } catch (DataXException e) {
        throw e;
    } catch (Exception e) {
        throw DataXException.asDataXException(DBUtilErrorCode.ILLEGAL_SPLIT_PK, "DataX尝试切分表发生错误. 请检查您的配置并作出修改.", e);
    } finally {
        DBUtil.closeDBResources(rs, null, null);
    }
    LOG.debug(JSON.toJSONString(splitedRange));
    List<String> rangeSql = new ArrayList<String>();
    int splitedRangeSize = splitedRange.size();
    // demo: Parameter rangeResult can not be null and its length can not <2. detail:rangeResult=[24999930].
    if (splitedRangeSize >= 2) {
        // warn: oracle Number is long type here
        if (isLongType(splitedRange.get(0).getRight())) {
            BigInteger[] integerPoints = new BigInteger[splitedRange.size()];
            for (int i = 0; i < splitedRangeSize; i++) {
                integerPoints[i] = new BigInteger(splitedRange.get(i).getLeft().toString());
            }
            rangeSql.addAll(RdbmsRangeSplitWrap.wrapRange(integerPoints, splitPK));
            // its ok if splitedRangeSize is 1
            rangeSql.add(RdbmsRangeSplitWrap.wrapFirstLastPoint(integerPoints[0], integerPoints[splitedRangeSize - 1], splitPK));
        } else if (isStringType(splitedRange.get(0).getRight())) {
            // warn: treated as string type
            String[] stringPoints = new String[splitedRange.size()];
            for (int i = 0; i < splitedRangeSize; i++) {
                stringPoints[i] = new String(splitedRange.get(i).getLeft().toString());
            }
            rangeSql.addAll(RdbmsRangeSplitWrap.wrapRange(stringPoints, splitPK, "'", DATABASE_TYPE));
            // its ok if splitedRangeSize is 1
            rangeSql.add(RdbmsRangeSplitWrap.wrapFirstLastPoint(stringPoints[0], stringPoints[splitedRangeSize - 1], splitPK, "'", DATABASE_TYPE));
        } else {
            throw DataXException.asDataXException(DBUtilErrorCode.ILLEGAL_SPLIT_PK, "您配置的DataX切分主键(splitPk)有误. 因为您配置的切分主键(splitPk) 类型 DataX 不支持. DataX 仅支持切分主键为一个,并且类型为整数或者字符串类型. 请尝试使用其他的切分主键或者联系 DBA 进行处理.");
        }
    }
    return rangeSql;
}
Also used : Connection(java.sql.Connection) ArrayList(java.util.ArrayList) DataXException(com.alibaba.datax.common.exception.DataXException) BigInteger(java.math.BigInteger) ResultSetMetaData(java.sql.ResultSetMetaData) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) DataXException(com.alibaba.datax.common.exception.DataXException) ResultSet(java.sql.ResultSet) BigInteger(java.math.BigInteger) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) Pair(org.apache.commons.lang3.tuple.Pair)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)13 Logger (org.slf4j.Logger)12 LoggerFactory (org.slf4j.LoggerFactory)12 ServicesManager (org.apereo.cas.services.ServicesManager)11 CasConfigurationProperties (org.apereo.cas.configuration.CasConfigurationProperties)9 Map (java.util.Map)8 PrincipalFactory (org.apereo.cas.authentication.principal.PrincipalFactory)7 Autowired (org.springframework.beans.factory.annotation.Autowired)7 ArrayList (java.util.ArrayList)6 Collection (java.util.Collection)6 Set (java.util.Set)6 AuthenticationEventExecutionPlan (org.apereo.cas.authentication.AuthenticationEventExecutionPlan)6 AuthenticationHandler (org.apereo.cas.authentication.AuthenticationHandler)6 DefaultPrincipalFactory (org.apereo.cas.authentication.principal.DefaultPrincipalFactory)6 AuthenticationEventExecutionPlanConfigurer (org.apereo.cas.config.support.authentication.AuthenticationEventExecutionPlanConfigurer)6 Qualifier (org.springframework.beans.factory.annotation.Qualifier)6 ConditionalOnMissingBean (org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean)6 RefreshScope (org.springframework.cloud.context.config.annotation.RefreshScope)6 Bean (org.springframework.context.annotation.Bean)6 Configuration (org.springframework.context.annotation.Configuration)6