Example usage for javax.security.auth.login Configuration getAppConfigurationEntry

List of usage examples for javax.security.auth.login Configuration getAppConfigurationEntry

Introduction

In this page you can find the example usage for javax.security.auth.login Configuration getAppConfigurationEntry.

Prototype

public abstract AppConfigurationEntry[] getAppConfigurationEntry(String name);

Source Link

Document

Retrieve the AppConfigurationEntries for the specified name from this Configuration.

Usage

From source file:it.cnr.icar.eric.client.xml.registry.jaas.LoginModuleManager.java

/*************************************************************************
 * private methods//  ww w.  j ava 2 s  .c  o m
 *************************************************************************/
@SuppressWarnings("unused")
private boolean getDebugSetting() {
    boolean debug = false;
    Configuration config = ConfigFile.getConfiguration();
    AppConfigurationEntry[] userAppConfigEntries = config.getAppConfigurationEntry(getApplicationName());

    for (int i = 0; i < userAppConfigEntries.length; i++) {
        Map<String, ?> options = userAppConfigEntries[i].getOptions();
        String debugStr = (String) options.get("debug");

        if (debugStr != null) {
            if (debugStr.equalsIgnoreCase("true")) {
                debug = true;
            }

            break;
        }
    }

    return debug;
}

From source file:it.cnr.icar.eric.client.xml.registry.jaas.LoginModuleManager.java

private void checkUserCfgFile(String userCfgFileName, String userCfgContents, String bundledFileContents)
        throws JAXRException {
    String userLoginName = getLoginName(userCfgContents);
    String bundledLoginName = getLoginName(bundledFileContents);

    // if the login names are the same, check attributes
    if (userLoginName.equalsIgnoreCase(bundledLoginName)) {
        // this method checks that any required attributes are present and
        // that fixed attributes are set according to the settings in the
        // bundled jaxr-ebxml.properties file.            
        Configuration config = ConfigFile.getConfiguration();
        String appName = getApplicationName();
        AppConfigurationEntry[] bundledAppConfigEntries = getReloadedAppConfigurationEntries(config,
                userCfgFileName + ".tmp", bundledFileContents, appName);
        AppConfigurationEntry[] userAppConfigEntries = config.getAppConfigurationEntry(appName);
        boolean isCorrect = areUserCfgFileAttributesCorrect(userAppConfigEntries, bundledAppConfigEntries);

        // if the user cfg content has changed, write it to the user cfg
        // file//from   w w w  . j av a 2s .c  o  m
        if (!isCorrect) {
            log.warn(JAXRResourceBundle.getInstance()
                    .getString("message.UserLoginConfigFileIsNotCorrectUsingBundledConfigFileInstead"));
            renameCfgFile(userCfgFileName, userCfgFileName + ".bak");
            log.info(JAXRResourceBundle.getInstance().getString("message.RenamedToBakFile",
                    new Object[] { userCfgFileName }));
            writeCfgFile(userCfgFileName, bundledFileContents, false);
            ConfigFile.getConfiguration().refresh();
            log.info(JAXRResourceBundle.getInstance().getString("message.createdNewLoginFile",
                    new Object[] { userCfgFileName }));
        } else {
            // if the user has a different keystore file in the 
            // jaxr-ebxml.properties file, update the user's config file
            // automatically.
            //TODO: check that it will not delete other entries
            updateUserCfgContents(userAppConfigEntries, userCfgContents, userCfgFileName);
        }
    } else {
        // the existing login name in different than the bundled. So, move 
        // the existing user cfg file to a backup file
        renameCfgFile(userCfgFileName, userCfgFileName + ".bak");
        writeCfgFile(userCfgFileName, bundledFileContents, false);
    }
}

From source file:it.cnr.icar.eric.client.xml.registry.jaas.LoginModuleManager.java

/**
 * This method is used to create the default login configuration file.
 * Currently, the default file is for the
 * com.sun.security.auth.module.KeystoreLoginModule
 *
 * @throws JAXRException/*  ww  w .ja  v  a  2s  .  c  o  m*/
 *  This is thrown if there is a problem writing the default login config
 *  file to the filesystem
 */
public void createDefaultLoginConfigFile() throws JAXRException {
    log.trace("start creation of default login config file");

    File keystoreFile = KeystoreUtil.getKeystoreFile();
    KeystoreUtil.canReadKeystoreFile(keystoreFile);

    // This property should always be set by java
    String userHomeFileName = System.getProperty("user.home");

    if ((userHomeFileName == null) || (userHomeFileName.length() == 0)) {
        throw new JAXRException(
                JAXRResourceBundle.getInstance().getString("message.error.not.find.system.property"));
    }

    File configFile;
    // Login config filename might be define as system property
    String configFileName = System.getProperty("java.security.auth.login.config");
    if (configFileName != null) {
        configFile = new File(configFileName);
    } else {
        configFile = new File(userHomeFileName, ".java.login.config");
    }

    if (configFile.exists()) {
        if (configFile.canRead()) {
            Configuration config = ConfigFile.getConfiguration();
            String appName = getApplicationName();
            AppConfigurationEntry[] defaultAppConfigEntries = getReloadedAppConfigurationEntries(config,
                    configFile.getPath() + ".tmp",
                    getDefaultConfigFileContents(DEFAULT_APPLICATION_NAME + ".tmp"), appName + ".tmp");
            AppConfigurationEntry[] userAppConfigEntries = config.getAppConfigurationEntry(appName);

            //TODO: Paul to verify this!! What if one of the Entries is null??
            boolean isCorrect;
            if (defaultAppConfigEntries == null && userAppConfigEntries == null) {
                // this will happen when using constructor LoginModuleManager(String applicationName)
                // and not having an entry for 'applicationName' in .java.login.config
                isCorrect = true;
            } else if (defaultAppConfigEntries != null && userAppConfigEntries == null) {
                // force add default to existing cfg file
                isCorrect = false;
            } else {
                isCorrect = checkLoginModules(userAppConfigEntries, defaultAppConfigEntries);
            }

            // if the user has a login config file with the same app name
            // as the default, but the login modules are different, rename
            // the existing user login config file and write the default
            // config file in place of the existing
            if (!isCorrect) {
                String userCfgFileName = configFile.getPath();
                String userCfgFileContent = getUserCfgFileContents(userCfgFileName);
                log.warn(JAXRResourceBundle.getInstance()
                        .getString("message.UserLoginConfigFileDoesNotHaveTheSameLoginModulesAsTheDefault"));
                renameCfgFile(userCfgFileName, userCfgFileName + ".bak");
                writeCfgFile(configFile, userCfgFileContent + LINE_SEPARATOR + getDefaultConfigFileContents(),
                        false);
                config.refresh();
                log.info(JAXRResourceBundle.getInstance().getString("message.createdNewLoginConfigFile",
                        new Object[] { configFile.getName() }));
            } else {
                log.info(JAXRResourceBundle.getInstance().getString("message.usingExistingConfigFile",
                        new Object[] { configFile.getName() }));

                return;
            }
        } else {
            throw new JAXRException(JAXRResourceBundle.getInstance().getString(
                    "message.error.file.not.readable", new Object[] { configFile.getAbsolutePath() }));
        }
    } else {
        writeCfgFile(configFile, getDefaultConfigFileContents(), false);
        log.info(JAXRResourceBundle.getInstance().getString("message.createdNewLoginConfigFile",
                new Object[] { configFile.getName() }));
    }

    log.trace("finish creation of default login config file");
}

From source file:it.cnr.icar.eric.client.xml.registry.jaas.LoginModuleManager.java

private AppConfigurationEntry[] getReloadedAppConfigurationEntries(Configuration config, String cfgFileName,
        String cfgFileContents, String appConfigName) throws JAXRException {
    AppConfigurationEntry[] appConfigEntries = null;

    // if there is an IOException, we do not have permission to write
    // to the local filesystem.  Without this permission, we cannot
    // control the authentication.  In this case, throw new 
    // JAXRException to notify the user to give us permission
    try {/*from ww  w.  j a va 2 s .  c om*/
        File file = new File(cfgFileName);
        writeCfgFile(file, cfgFileContents, false);
    } catch (Throwable t) {
        log.error(t);
        throw new JAXRException(JAXRResourceBundle.getInstance()
                .getString("message.error.no.permission.wirte.local.filesystem"));
    }

    String javaSecLoginCfg = System.getProperty("java.security.auth.login.config");
    String userCfgFileName = getUserCfgFileName();
    System.setProperty("java.security.auth.login.config", cfgFileName);
    config.refresh();
    appConfigEntries = config.getAppConfigurationEntry(appConfigName);

    try {
        deleteCfgFile(cfgFileName);
    } catch (Throwable t) {
        log.warn(JAXRResourceBundle.getInstance().getString("message.problemDeletingConfigFile"), t);
    } finally {
        if (javaSecLoginCfg != null) {
            System.setProperty("java.security.auth.login.config", javaSecLoginCfg);
        } else {
            System.setProperty("java.security.auth.login.config", userCfgFileName);
        }

        config.refresh();
    }

    return appConfigEntries;
}

From source file:org.apache.activemq.artemis.spi.core.security.jaas.PropertiesLoginModuleConfigurator.java

public PropertiesLoginModuleConfigurator(String entryName, String brokerEtc) throws Exception {
    if (entryName == null || entryName.length() == 0) {
        entryName = "activemq";
    }// www .ja  va 2 s. c o  m

    Configuration securityConfig = Configuration.getConfiguration();
    AppConfigurationEntry[] entries = securityConfig.getAppConfigurationEntry(entryName);

    if (entries == null || entries.length == 0) {
        throw ActiveMQMessageBundle.BUNDLE.failedToLoadSecurityConfig();
    }

    int entriesInspected = 0;
    for (AppConfigurationEntry entry : entries) {
        entriesInspected++;
        if (entry.getLoginModuleName().equals(PropertiesLoginModule.class.getName())) {
            String userFileName = (String) entry.getOptions().get(USER_FILE_PROP_NAME);
            String roleFileName = (String) entry.getOptions().get(ROLE_FILE_PROP_NAME);

            File etcDir = new File(brokerEtc);
            File userFile = new File(etcDir, userFileName);
            File roleFile = new File(etcDir, roleFileName);

            if (!userFile.exists()) {
                throw ActiveMQMessageBundle.BUNDLE.failedToLoadUserFile(brokerEtc + userFileName);
            }

            if (!roleFile.exists()) {
                throw ActiveMQMessageBundle.BUNDLE.failedToLoadRoleFile(brokerEtc + roleFileName);
            }

            Configurations configs = new Configurations();
            userBuilder = configs.propertiesBuilder(userFile);
            roleBuilder = configs.propertiesBuilder(roleFile);
            userConfig = userBuilder.getConfiguration();
            roleConfig = roleBuilder.getConfiguration();

            String roleHeader = roleConfig.getLayout().getHeaderComment();
            String userHeader = userConfig.getLayout().getHeaderComment();

            if (userHeader == null) {
                if (userConfig.isEmpty()) {
                    //clean and reset header
                    userConfig.clear();
                    userConfig.setHeader(LICENSE_HEADER);
                }
            }

            if (roleHeader == null) {
                if (roleConfig.isEmpty()) {
                    //clean and reset header
                    roleConfig.clear();
                    roleConfig.setHeader(LICENSE_HEADER);
                }
            }
            return;
        }
    }

    if (entriesInspected == entries.length) {
        throw ActiveMQMessageBundle.BUNDLE.failedToFindLoginModuleEntry(entryName);
    }
}

From source file:org.apache.nifi.processors.solr.SolrProcessor.java

@Override
protected final Collection<ValidationResult> customValidate(ValidationContext context) {
    final List<ValidationResult> problems = new ArrayList<>();

    if (SOLR_TYPE_CLOUD.equals(context.getProperty(SOLR_TYPE).getValue())) {
        final String collection = context.getProperty(COLLECTION).getValue();
        if (collection == null || collection.trim().isEmpty()) {
            problems.add(new ValidationResult.Builder().subject(COLLECTION.getName()).input(collection)
                    .valid(false).explanation("A collection must specified for Solr Type of Cloud").build());
        }/* www .jav  a2s .c o  m*/
    }

    // If a JAAS Client App Name is provided then the system property for the JAAS config file must be set,
    // and that config file must contain an entry for the name provided by the processor
    final String jaasAppName = context.getProperty(JAAS_CLIENT_APP_NAME).getValue();
    if (!StringUtils.isEmpty(jaasAppName)) {
        final String loginConf = System.getProperty(Krb5HttpClientConfigurer.LOGIN_CONFIG_PROP);
        if (StringUtils.isEmpty(loginConf)) {
            problems.add(
                    new ValidationResult.Builder().subject(JAAS_CLIENT_APP_NAME.getDisplayName()).valid(false)
                            .explanation("the system property " + Krb5HttpClientConfigurer.LOGIN_CONFIG_PROP
                                    + " must be set when providing a JAAS Client App Name")
                            .build());
        } else {
            final Configuration config = javax.security.auth.login.Configuration.getConfiguration();
            if (config.getAppConfigurationEntry(jaasAppName) == null) {
                problems.add(new ValidationResult.Builder().subject(JAAS_CLIENT_APP_NAME.getDisplayName())
                        .valid(false).explanation("'" + jaasAppName + "' does not exist in " + loginConf)
                        .build());
            }
        }
    }

    // For solr cloud the location will be the ZooKeeper host:port so we can't validate the SSLContext, but for standard solr
    // we can validate if the url starts with https we need an SSLContextService, if it starts with http we can't have an SSLContextService
    if (SOLR_TYPE_STANDARD.equals(context.getProperty(SOLR_TYPE).getValue())) {
        final String solrLocation = context.getProperty(SOLR_LOCATION).evaluateAttributeExpressions()
                .getValue();
        if (solrLocation != null) {
            final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE)
                    .asControllerService(SSLContextService.class);
            if (solrLocation.startsWith("https:") && sslContextService == null) {
                problems.add(new ValidationResult.Builder().subject(SSL_CONTEXT_SERVICE.getDisplayName())
                        .valid(false).explanation("an SSLContextService must be provided when using https")
                        .build());
            } else if (solrLocation.startsWith("http:") && sslContextService != null) {
                problems.add(new ValidationResult.Builder().subject(SSL_CONTEXT_SERVICE.getDisplayName())
                        .valid(false).explanation("an SSLContextService can not be provided when using http")
                        .build());
            }
        }
    }

    // Validate that we username and password are provided together, or that neither are provided
    final String username = context.getProperty(BASIC_USERNAME).evaluateAttributeExpressions().getValue();
    final String password = context.getProperty(BASIC_PASSWORD).evaluateAttributeExpressions().getValue();

    if (!StringUtils.isBlank(username) && StringUtils.isBlank(password)) {
        problems.add(new ValidationResult.Builder().subject(BASIC_PASSWORD.getDisplayName()).valid(false)
                .explanation("a password must be provided for the given username").build());
    }

    if (!StringUtils.isBlank(password) && StringUtils.isBlank(username)) {
        problems.add(new ValidationResult.Builder().subject(BASIC_USERNAME.getDisplayName()).valid(false)
                .explanation("a username must be provided for the given password").build());
    }

    Collection<ValidationResult> otherProblems = this.additionalCustomValidation(context);
    if (otherProblems != null) {
        problems.addAll(otherProblems);
    }

    return problems;
}

From source file:org.apache.ranger.audit.provider.MiscUtil.java

public static void authWithConfig(String appName, Configuration config) {
    try {//www.  j a v  a  2s .c o m
        if (config != null) {
            logger.info(
                    "Getting AppConfigrationEntry[] for appName=" + appName + ", config=" + config.toString());
            AppConfigurationEntry[] entries = config.getAppConfigurationEntry(appName);
            if (entries != null) {
                logger.info("Got " + entries.length + "  AppConfigrationEntry elements for appName=" + appName);
                for (AppConfigurationEntry appEntry : entries) {
                    logger.info("APP_ENTRY:getLoginModuleName()=" + appEntry.getLoginModuleName());
                    logger.info("APP_ENTRY:getControlFlag()=" + appEntry.getControlFlag());
                    logger.info("APP_ENTRY.getOptions()=" + appEntry.getOptions());
                }
            }

            LoginContext loginContext = new LoginContext(appName, new Subject(), null, config);
            logger.info("Login in for appName=" + appName);
            loginContext.login();
            logger.info("Principals after login=" + loginContext.getSubject().getPrincipals());
            logger.info("UserGroupInformation.loginUserFromSubject(): appName=" + appName + ", principals="
                    + loginContext.getSubject().getPrincipals());

            UserGroupInformation ugi = MiscUtil.createUGIFromSubject(loginContext.getSubject());
            if (ugi != null) {
                MiscUtil.setUGILoginUser(ugi, loginContext.getSubject());
            }

            // UserGroupInformation.loginUserFromSubject(loginContext
            // .getSubject());
            logger.info("POST UserGroupInformation.loginUserFromSubject UGI="
                    + UserGroupInformation.getLoginUser());
        }
    } catch (Throwable t) {
        logger.fatal("Error logging as appName=" + appName + ", config=" + config.toString() + ", error="
                + t.getMessage());
    }
}

From source file:org.apache.storm.security.auth.AuthUtils.java

/**
 * Get configurations for a section/*from   ww  w.j  a v  a  2  s .  c o  m*/
 * @param configuration The config to pull the key/value pairs out of.
 * @param section The app configuration entry name to get stuff from.
 * @return Return array of config entries or null if configuration is null
 */
public static AppConfigurationEntry[] getEntries(Configuration configuration, String section)
        throws IOException {
    if (configuration == null) {
        return null;
    }

    AppConfigurationEntry configurationEntries[] = configuration.getAppConfigurationEntry(section);
    if (configurationEntries == null) {
        String errorMessage = "Could not find a '" + section + "' entry in this configuration.";
        throw new IOException(errorMessage);
    }
    return configurationEntries;
}

From source file:org.apache.storm.security.auth.AuthUtilsTest.java

@Test
public void getNonExistentSectionTest() throws IOException {
    Map<String, String> optionMap = new HashMap<String, String>();
    AppConfigurationEntry entry = Mockito.mock(AppConfigurationEntry.class);

    Mockito.<Map<String, ?>>when(entry.getOptions()).thenReturn(optionMap);
    String section = "bogus-section";
    Configuration mockConfig = Mockito.mock(Configuration.class);
    Mockito.when(mockConfig.getAppConfigurationEntry(section))
            .thenReturn(new AppConfigurationEntry[] { entry });
    Assert.assertNull(AuthUtils.get(mockConfig, section, "nonexistent-key"));
}

From source file:org.apache.storm.security.auth.AuthUtilsTest.java

@Test
public void getFirstValueForValidKeyTest() throws IOException {
    String k = "the-key";
    String expected = "good-value";

    Map<String, String> optionMap = new HashMap<String, String>();
    optionMap.put(k, expected);/*  www.j av  a2  s.  c  om*/

    Map<String, String> badOptionMap = new HashMap<String, String>();
    badOptionMap.put(k, "bad-value");

    AppConfigurationEntry emptyEntry = Mockito.mock(AppConfigurationEntry.class);
    AppConfigurationEntry badEntry = Mockito.mock(AppConfigurationEntry.class);
    AppConfigurationEntry goodEntry = Mockito.mock(AppConfigurationEntry.class);

    Mockito.<Map<String, ?>>when(emptyEntry.getOptions()).thenReturn(new HashMap<String, String>());
    Mockito.<Map<String, ?>>when(badEntry.getOptions()).thenReturn(badOptionMap);
    Mockito.<Map<String, ?>>when(goodEntry.getOptions()).thenReturn(optionMap);

    String section = "bogus-section";
    Configuration mockConfig = Mockito.mock(Configuration.class);
    Mockito.when(mockConfig.getAppConfigurationEntry(section))
            .thenReturn(new AppConfigurationEntry[] { emptyEntry, goodEntry, badEntry });

    Assert.assertEquals(AuthUtils.get(mockConfig, section, k), expected);
}