Example usage for javax.naming Context SECURITY_AUTHENTICATION

List of usage examples for javax.naming Context SECURITY_AUTHENTICATION

Introduction

In this page you can find the example usage for javax.naming Context SECURITY_AUTHENTICATION.

Prototype

String SECURITY_AUTHENTICATION

To view the source code for javax.naming Context SECURITY_AUTHENTICATION.

Click Source Link

Document

Constant that holds the name of the environment property for specifying the security level to use.

Usage

From source file:org.jkcsoft.java.util.JndiHelper.java

public static DirContext getDirContext(BehavioralContext bctx, Object principal, Object credentials)
        throws NamingException {
    DirContext ctx = null;//from  w  w w  .  ja v a 2  s.co m

    Configuration tconfig = bctx.getConfig();
    String ldapProvider = "ldap" + "://" + tconfig.getString(Constants.KEY_AD_HOST) + ":"
            + tconfig.getString(Constants.KEY_AD_PORT) + "/" + tconfig.getString(Constants.KEY_AD_ROOT_DN);

    log.info("Using LDAP url: [" + ldapProvider + "]");

    //        String url, String contextFactoryName,

    Hashtable jndiEnv = new Hashtable();

    jndiEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    jndiEnv.put(Context.PROVIDER_URL, ldapProvider);
    jndiEnv.put(Context.REFERRAL, "follow");

    if (tconfig.getBoolean(Constants.KEY_AD_SSL)) {
        log.info("Using SSL for LDAP");
        jndiEnv.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    jndiEnv.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (principal != null)
        jndiEnv.put(Context.SECURITY_PRINCIPAL, principal);

    if (credentials != null)
        jndiEnv.put(Context.SECURITY_CREDENTIALS, credentials);

    try {
        // Creating the JNDI directory context (with LDAP context
        // factory), performs an LDAP bind to the LDAP provider thereby
        // authenticating the username/pw.
        ctx = new InitialDirContext(jndiEnv);
    } catch (NamingException ex) {
        log.error("Directory context init failed", ex);
        throw ex;
    }

    return ctx;
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Creates an InitialLdapContext by logging into the configured Ldap Server using the provided
 * username and credential.//from   w  ww  .  j a  va 2  s  .  co  m
 *
 * @return the Initial Ldap Context to be used to perform searches, etc.
 * @throws NamingException LDAP binding error.
 */
protected InitialLdapContext createLdapInitialContext(String securityPrincipal, String securityCredential)
        throws NamingException {

    Properties env = new Properties();

    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory());
    env.setProperty(Context.SECURITY_AUTHENTICATION, getSecurityAuthentication());
    env.setProperty(Context.PROVIDER_URL, getProviderUrl());
    env.setProperty(Context.SECURITY_PROTOCOL, (getSecurityProtocol() == null ? "" : getSecurityProtocol()));

    // Set defaults for key values if they are missing

    String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    if (factoryName == null) {
        factoryName = "com.sun.jndi.ldap.LdapCtxFactory";
        env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
    }

    String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);
    if (authType == null)
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");

    String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
    String providerURL = getProviderUrl();
    // Use localhost if providerUrl not set
    if (providerURL == null) {
        //providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");
        if (protocol != null && protocol.equals("ssl")) {
            // We should use Start TLS extension?
            providerURL = "ldaps://localhost:636";
        } else {
            providerURL = "ldap://localhost:389";
        }
    }

    env.setProperty(Context.PROVIDER_URL, providerURL);
    env.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredential);

    // always follow referrals transparently
    env.put(Context.REFERRAL, "follow");

    // Logon into LDAP server
    if (logger.isDebugEnabled())
        logger.debug("Logging into LDAP server, env=" + env);

    InitialLdapContext ctx = new InitialLdapContext(env, null);

    if (logger.isDebugEnabled())
        logger.debug("Logged into LDAP server, " + ctx);

    return ctx;
}

From source file:org.jsecurity.realm.ldap.DefaultLdapContextFactory.java

public LdapContext getLdapContext(String username, String password) throws NamingException {
    if (searchBase == null) {
        throw new IllegalStateException("A search base must be specified.");
    }/*from w ww .j  a  v  a2  s .  c o m*/
    if (url == null) {
        throw new IllegalStateException("An LDAP URL must be specified of the form ldap://<hostname>:<port>");
    }

    if (username != null && principalSuffix != null) {
        username += principalSuffix;
    }

    Hashtable<String, String> env = new Hashtable<String, String>();

    env.put(Context.SECURITY_AUTHENTICATION, authentication);
    if (username != null) {
        env.put(Context.SECURITY_PRINCIPAL, username);
    }
    if (password != null) {
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactoryClassName);
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.REFERRAL, referral);

    // Only pool connections for system contexts
    if (usePooling && username != null && username.equals(systemUsername)) {
        // Enable connection pooling
        env.put(SUN_CONNECTION_POOLING_PROPERTY, "true");
    }

    if (additionalEnvironment != null) {
        env.putAll(additionalEnvironment);
    }

    if (log.isDebugEnabled()) {
        log.debug("Initializing LDAP context using URL [" + url + "] and username [" + systemUsername + "] "
                + "with pooling [" + (usePooling ? "enabled" : "disabled") + "]");
    }

    return new InitialLdapContext(env, null);
}

From source file:org.kitodo.production.services.data.LdapServerService.java

private Hashtable<String, String> initializeWithLdapConnectionSettings(LdapServer ldapServer) {
    Hashtable<String, String> env = new Hashtable<>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapServer.getUrl());
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, ldapServer.getManagerLogin());

    String encryptedManagerPassword = ldapServer.getManagerPassword();
    String decryptedManagerPassword = passwordEncoder.decrypt(encryptedManagerPassword);

    env.put(Context.SECURITY_CREDENTIALS, decryptedManagerPassword);

    if (ldapServer.isUseSsl()) {
        String keystorepath = ldapServer.getKeystore();
        String keystorepasswd = ldapServer.getKeystorePassword();

        // add all necessary certificates first
        loadCertificates(keystorepath, keystorepasswd, ldapServer);

        // set properties, so that the current keystore is used for SSL
        System.setProperty("javax.net.ssl.keyStore", keystorepath);
        System.setProperty("javax.net.ssl.trustStore", keystorepath);
        System.setProperty("javax.net.ssl.keyStorePassword", keystorepasswd);
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }/*from   w  w  w .j  av a2s.  co  m*/
    return env;
}

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * Retrieve home directory of given user.
 *
 * @param user/*from   w  w w.j a v  a2  s.  c o  m*/
 *            User object
 * @return path as URI
 */
public URI getUserHomeDirectory(User user) {
    String userFolderBasePath = ConfigCore.getParameter(ParameterCore.DIR_USERS);

    if (ConfigCore.getBooleanParameterOrDefaultValue(ParameterCore.LDAP_USE_LOCAL_DIRECTORY)) {
        return Paths.get(userFolderBasePath, user.getLogin()).toUri();
    }
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());
    if (ConfigCore.getBooleanParameterOrDefaultValue(ParameterCore.LDAP_USE_TLS)) {
        return getUserHomeDirectoryWithTLS(env, userFolderBasePath, user);
    }

    if (ConfigCore.getBooleanParameter(ParameterCore.LDAP_USE_SIMPLE_AUTH, false)) {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx;
    URI userFolderPath = null;
    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(buildUserDN(user));
        Attribute ldapAttribute = attrs.get("homeDirectory");
        userFolderPath = URI.create((String) ldapAttribute.get(0));
        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }

    if (Objects.nonNull(userFolderPath) && !userFolderPath.isAbsolute()) {
        if (userFolderPath.getPath().startsWith("/")) {
            userFolderPath = ServiceManager.getFileService().deleteFirstSlashFromPath(userFolderPath);
        }
        return Paths.get(userFolderBasePath, userFolderPath.getRawPath()).toUri();
    } else {
        return userFolderPath;
    }
}

From source file:org.kitodo.production.services.data.LdapServerService.java

private boolean isPasswordCorrectForAuthWithTLS(Hashtable<String, String> env, User user, String password) {
    env.put("java.naming.ldap.version", "3");
    LdapContext ctx = null;//from   w  w  w  .  ja  v  a 2  s  .  co  m
    StartTlsResponse tls = null;
    try {
        ctx = new InitialLdapContext(env, null);

        // Authentication must be performed over a secure channel
        tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        tls.negotiate();

        // Authenticate via SASL EXTERNAL mechanism using client X.509
        // certificate contained in JVM keystore
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, buildUserDN(user));
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        ctx.reconnect(null);
        return true;
        // perform search for privileged attributes under authenticated context
    } catch (IOException e) {
        logger.error("TLS negotiation error:", e);
        return false;
    } catch (NamingException e) {
        logger.error("JNDI error:", e);
        return false;
    } finally {
        closeConnections(ctx, tls);
    }
}

From source file:org.kitodo.production.services.data.LdapServerService.java

private boolean isPasswordCorrectForAuthWithoutTLS(Hashtable<String, String> env, User user, String password) {
    if (ConfigCore.getBooleanParameter(ParameterCore.LDAP_USE_SIMPLE_AUTH, false)) {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
        // TODO: test for password
    } else {// ww  w  .  j  ava2  s  .co  m
        env.put(Context.SECURITY_PRINCIPAL, buildUserDN(user));
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    logger.debug("ldap environment set");

    try {
        logger.debug("start classic ldap authentication");
        logger.debug("user DN is {}", buildUserDN(user));

        if (Objects.isNull(ConfigCore.getParameter(ParameterCore.LDAP_ATTRIBUTE_TO_TEST))) {
            logger.debug("ldap attribute to test is null");
            DirContext ctx = new InitialDirContext(env);
            ctx.close();
            return true;
        } else {
            logger.debug("ldap attribute to test is not null");
            DirContext ctx = new InitialDirContext(env);

            Attributes attrs = ctx.getAttributes(buildUserDN(user));
            Attribute la = attrs.get(ConfigCore.getParameter(ParameterCore.LDAP_ATTRIBUTE_TO_TEST));
            logger.debug("ldap attributes set");
            String test = (String) la.get(0);
            if (test.equals(ConfigCore.getParameter(ParameterCore.LDAP_VALUE_OF_ATTRIBUTE))) {
                logger.debug("ldap ok");
                ctx.close();
                return true;
            } else {
                logger.debug("ldap not ok");
                ctx.close();
                return false;
            }
        }
    } catch (NamingException e) {
        logger.debug("login not allowed for {}. Exception: {}", user.getLogin(), e);
        return false;
    }
}

From source file:org.kitodo.services.data.LdapServerService.java

/**
 * Check if connection with login and password possible.
 *
 * @param user// w  w w .  ja v  a 2 s. c o m
 *            User object
 * @param password
 *            String
 * @return Login correct or not
 */
public boolean isUserPasswordCorrect(User user, String password) {
    logger.debug("start login session with ldap");
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());

    // Start TLS
    if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) {
        logger.debug("use TLS for auth");
        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            // Authenticate via SASL EXTERNAL mechanism using client X.509
            // certificate contained in JVM keystore
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, buildUserDN(user));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
            ctx.reconnect(null);
            return true;
            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);
            return false;
        } catch (NamingException e) {
            logger.error("JNDI error:", e);
            return false;
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    } else {
        logger.debug("don't use TLS for auth");
        if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
            env.put(Context.SECURITY_AUTHENTICATION, "none");
            // TODO auf passwort testen
        } else {
            env.put(Context.SECURITY_PRINCIPAL, buildUserDN(user));
            env.put(Context.SECURITY_CREDENTIALS, password);
        }
        logger.debug("ldap environment set");

        try {
            logger.debug("start classic ldap authentication");
            logger.debug("user DN is {}", buildUserDN(user));

            if (ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST) == null) {
                logger.debug("ldap attribute to test is null");
                DirContext ctx = new InitialDirContext(env);
                ctx.close();
                return true;
            } else {
                logger.debug("ldap attribute to test is not null");
                DirContext ctx = new InitialDirContext(env);

                Attributes attrs = ctx.getAttributes(buildUserDN(user));
                Attribute la = attrs.get(ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST));
                logger.debug("ldap attributes set");
                String test = (String) la.get(0);
                if (test.equals(ConfigCore.getParameter(Parameters.LDAP_VALUE_OF_ATTRIBUTE))) {
                    logger.debug("ldap ok");
                    ctx.close();
                    return true;
                } else {
                    logger.debug("ldap not ok");
                    ctx.close();
                    return false;
                }
            }
        } catch (NamingException e) {
            logger.debug("login not allowed for {}. Exception: {}", user.getLogin(), e);
            return false;
        }
    }
}

From source file:org.kitodo.services.data.LdapServerService.java

/**
 * Retrieve home directory of given user.
 *
 * @param user/*from  w w  w . j  a v a2  s  .c o  m*/
 *            User object
 * @return path as URI
 */
public URI getUserHomeDirectory(User user) {

    URI userFolderBasePath = URI.create("file:///" + ConfigCore.getParameter(Parameters.DIR_USERS));

    if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_LOCAL_DIRECTORY)) {
        return userFolderBasePath.resolve(user.getLogin());
    }
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());
    if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) {

        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            ctx.reconnect(null);

            Attributes attrs = ctx.getAttributes(buildUserDN(user));
            Attribute la = attrs.get("homeDirectory");
            return URI.create((String) la.get(0));

            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);

            return userFolderBasePath.resolve(user.getLogin());
        } catch (NamingException e) {

            logger.error("JNDI error:", e);

            return userFolderBasePath.resolve(user.getLogin());
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }
    if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx;
    URI userFolderPath = null;
    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(buildUserDN(user));
        Attribute ldapAttribute = attrs.get("homeDirectory");
        userFolderPath = URI.create((String) ldapAttribute.get(0));
        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }

    if (userFolderPath != null && !userFolderPath.isAbsolute()) {
        if (userFolderPath.getPath().startsWith("/")) {
            userFolderPath = serviceManager.getFileService().deleteFirstSlashFromPath(userFolderPath);
        }
        return userFolderBasePath.resolve(userFolderPath);
    } else {
        return userFolderPath;
    }
}

From source file:org.liveSense.auth.ldap.LdapAuthenticationHandler.java

boolean isLdapValid(final Credentials credentials) throws RepositoryException {
    LdapUser ldapUser = getLdapAuthData(credentials);
    if (ldapUser != null) {
        Hashtable<String, String> authEnv = new Hashtable<String, String>(11);
        //String dn = "uid=" + ldapUser.getUserName() + "," + ldapBase;
        String dn = StringUtils.replace(ldapBase, "${userName}", ldapUser.getUserName());
        authEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        authEnv.put(Context.PROVIDER_URL, ldapUrl);
        authEnv.put(Context.SECURITY_AUTHENTICATION, ldapAuthenticationType);
        authEnv.put(Context.SECURITY_PRINCIPAL, dn);
        authEnv.put(Context.SECURITY_CREDENTIALS, ldapUser.getPassword());
        try {//ww w.  j av  a2 s.  com
            DirContext ctx = new InitialDirContext(authEnv);
            Attributes attributes = ctx.getAttributes(dn);
            ldapUser.setAttributes(attributes);
            return true;
        } catch (AuthenticationException authEx) {
            return false;

        } catch (NamingException namEx) {
            throw new RepositoryException("Ldap Error:" + namEx.getExplanation());
        }
    }
    // no authdata, not valid
    return false;
}