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.apache.directory.server.operations.bind.MiscBindIT.java

@Test
public void testFailureWithUnsupportedControl() throws Exception {
    Control unsupported = new OpaqueControl("1.1.1.1");
    unsupported.setCritical(true);//  ww w  .j  a  va 2s . c  om

    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

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

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()) + "/ou=system");
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    InitialLdapContext ctx = new InitialLdapContext(env, null);

    Attributes user = new BasicAttributes("cn", "Kate Bush", true);
    Attribute oc = new BasicAttribute("objectClass");
    oc.add("top");
    oc.add("person");
    oc.add("organizationalPerson");
    oc.add("inetOrgPerson");
    user.put(oc);
    user.put("sn", "Bush");
    user.put("userPassword", "Aerial");
    ctx.setRequestControls(JndiUtils.toJndiControls(getLdapServer().getDirectoryService().getLdapCodecService(),
            new Control[] { unsupported }));

    try {
        ctx.createSubcontext("cn=Kate Bush", user);
        fail();
    } catch (OperationNotSupportedException e) {
    }

    unsupported.setCritical(false);
    ctx.setRequestControls(JndiUtils.toJndiControls(getLdapServer().getDirectoryService().getLdapCodecService(),
            new Control[] { unsupported }));

    DirContext kate = ctx.createSubcontext("cn=Kate Bush", user);
    assertNotNull(kate);
    assertTrue(ArrayUtils.isEquals(Asn1StringUtils.getBytesUtf8("Aerial"),
            kate.getAttributes("").get("userPassword").get()));

    ctx.destroySubcontext("cn=Kate Bush");
}

From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java

/**
 * Gets and returns the entries from the server.
 * /*from  ww  w  .j  a  v a 2s .  c o m*/
 * @throws ToolCommandException
 * @throws NamingException
 */
public NamingEnumeration connectToServerAndGetEntries() throws ToolCommandException {
    // Connecting to the LDAP Server
    if (isDebugEnabled()) {
        notifyOutputListener("Connecting to LDAP server");
        notifyOutputListener("Host: " + host);
        notifyOutputListener("Port: " + port);
        notifyOutputListener("User DN: " + user);
        notifyOutputListener("Base DN: " + baseDN);
        notifyOutputListener("Authentication: " + auth);
    }
    Hashtable env = new Hashtable();
    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, auth);
    env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port + "/" + baseDN);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    DirContext ctx;
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException e) {
        throw new ToolCommandException("Could not connect to the server.\nError: " + e.getMessage());
    }

    // Setting up search scope
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(scope);

    // Fetching entries
    try {
        return ctx.search(exportPoint, "(objectClass=*)", ctls);
    } catch (NamingException e) {
        throw new ToolCommandException("Could not retreive entries");
    }
}

From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

private void doBind(final StudioProgressMonitor monitor) throws NamingException {
    if (context != null && isConnected) {
        // setup authentication methdod
        authMethod = AUTHMETHOD_NONE;/*ww  w . j  a  v a  2  s .c  o  m*/
        if (connection.getConnectionParameter()
                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SIMPLE) {
            authMethod = AUTHMETHOD_SIMPLE;
        } else if (connection.getConnectionParameter()
                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_DIGEST_MD5) {
            authMethod = AUTHMETHOD_DIGEST_MD5;
            saslRealm = connection.getConnectionParameter().getSaslRealm();
        } else if (connection.getConnectionParameter()
                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_CRAM_MD5) {
            authMethod = AUTHMETHOD_CRAM_MD5;
        } else if (connection.getConnectionParameter()
                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_GSSAPI) {
            authMethod = AUTHMETHOD_GSSAPI;
        }

        // No Authentication
        if (authMethod == AUTHMETHOD_NONE) {
            bindPrincipal = ""; //$NON-NLS-1$
            bindCredentials = ""; //$NON-NLS-1$
        } else {
            // setup credentials
            IAuthHandler authHandler = ConnectionCorePlugin.getDefault().getAuthHandler();
            if (authHandler == null) {
                NamingException namingException = new NamingException(Messages.model__no_auth_handler);
                monitor.reportError(Messages.model__no_auth_handler, namingException);
                throw namingException;
            }
            ICredentials credentials = authHandler.getCredentials(connection.getConnectionParameter());
            if (credentials == null) {
                CancelException cancelException = new CancelException();
                monitor.setCanceled(true);
                monitor.reportError(Messages.model__no_credentials, cancelException);
                throw cancelException;
            }
            if (credentials.getBindPrincipal() == null || credentials.getBindPassword() == null) {
                NamingException namingException = new NamingException(Messages.model__no_credentials);
                monitor.reportError(Messages.model__no_credentials, namingException);
                throw namingException;
            }
            bindPrincipal = credentials.getBindPrincipal();
            bindCredentials = credentials.getBindPassword();
        }

        InnerRunnable runnable = new InnerRunnable() {
            public void run() {
                try {
                    context.removeFromEnvironment(Context.SECURITY_AUTHENTICATION);
                    context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
                    context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
                    context.removeFromEnvironment(JAVA_NAMING_SECURITY_SASL_REALM);

                    context.addToEnvironment(Context.SECURITY_AUTHENTICATION, authMethod);

                    // SASL options
                    if (connection.getConnectionParameter()
                            .getAuthMethod() == AuthenticationMethod.SASL_CRAM_MD5
                            || connection.getConnectionParameter()
                                    .getAuthMethod() == AuthenticationMethod.SASL_DIGEST_MD5
                            || connection.getConnectionParameter()
                                    .getAuthMethod() == AuthenticationMethod.SASL_GSSAPI) {
                        // Request quality of protection
                        switch (connection.getConnectionParameter().getSaslQop()) {
                        case AUTH:
                            context.addToEnvironment(Sasl.QOP, SaslQoP.AUTH.getValue());
                            break;
                        case AUTH_INT:
                            context.addToEnvironment(Sasl.QOP, SaslQoP.AUTH_INT.getValue());
                            break;
                        case AUTH_CONF:
                            context.addToEnvironment(Sasl.QOP, SaslQoP.AUTH_CONF.getValue());
                            break;
                        }

                        // Request mutual authentication
                        if (connection.getConnectionParameter().isSaslMutualAuthentication()) {
                            context.addToEnvironment(Sasl.SERVER_AUTH, "true"); //$NON-NLS-1$
                        } else {
                            context.removeFromEnvironment(Sasl.SERVER_AUTH);
                        }

                        // Request cryptographic protection strength
                        switch (connection.getConnectionParameter().getSaslSecurityStrength()) {
                        case HIGH:
                            context.addToEnvironment(Sasl.STRENGTH, SaslSecurityStrength.HIGH.getValue());
                            break;
                        case MEDIUM:
                            context.addToEnvironment(Sasl.STRENGTH, SaslSecurityStrength.MEDIUM.getValue());
                            break;
                        case LOW:
                            context.addToEnvironment(Sasl.STRENGTH, SaslSecurityStrength.LOW.getValue());
                            break;
                        }
                    }

                    // Bind
                    if (connection.getConnectionParameter()
                            .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_GSSAPI) {
                        // GSSAPI
                        doGssapiBind(this);
                    } else {
                        // no GSSAPI
                        context.addToEnvironment(Context.SECURITY_PRINCIPAL, bindPrincipal);
                        context.addToEnvironment(Context.SECURITY_CREDENTIALS, bindCredentials);

                        if (connection.getConnectionParameter()
                                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_DIGEST_MD5
                                && StringUtils.isNotEmpty(saslRealm)) {
                            context.addToEnvironment(JAVA_NAMING_SECURITY_SASL_REALM, saslRealm);
                        }

                        context.reconnect(context.getConnectControls());
                    }
                } catch (NamingException ne) {
                    namingException = ne;
                }
            }
        };

        runAndMonitor(runnable, monitor);

        if (runnable.getException() != null) {
            throw runnable.getException();
        } else if (context != null) {
            // all OK
        } else {
            throw new NamingException("???"); //$NON-NLS-1$
        }
    } else {
        throw new NamingException(NO_CONNECTION);
    }
}

From source file:org.apache.ftpserver.usermanager.LdapUserManager.java

/**
 * Instantiate LDAP based <code>UserManager</code> implementation.
 *///from   w ww. j av  a2s. c  o  m
public void configure(Configuration config) throws FtpException {

    try {

        // get admin name 
        m_adminName = config.getString("admin", "admin");

        // get ldap parameters
        String url = config.getString("ldap-url");
        String admin = config.getString("ldap-admin-dn");
        String password = config.getString("ldap-admin-password");
        String auth = config.getString("ldap-authentication", "simple");

        m_userBaseDn = config.getString("ldap-user-base-dn");

        // create connection
        Properties adminEnv = new Properties();
        adminEnv.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        adminEnv.setProperty(Context.PROVIDER_URL, url);
        adminEnv.setProperty(Context.SECURITY_AUTHENTICATION, auth);
        adminEnv.setProperty(Context.SECURITY_PRINCIPAL, admin);
        adminEnv.setProperty(Context.SECURITY_CREDENTIALS, password);
        m_adminContext = new InitialDirContext(adminEnv);

        // create objectClass attribute
        m_objClassAttr = new BasicAttribute(OBJ_CLASS, false);
        m_objClassAttr.add("javaObject");
        m_objClassAttr.add("top");

        m_log.info("LDAP user manager opened.");
    } catch (FtpException ex) {
        throw ex;
    } catch (Exception ex) {
        m_log.fatal("LdapUserManager.configure()", ex);
        throw new FtpException("LdapUserManager.configure()", ex);
    }
}

From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

protected DirContext open() throws NamingException {
    if (context != null) {
        return context;
    }/*from  w  ww .  ja  v  a 2s.co  m*/
    try {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
        if (connectionUsername != null || !"".equals(connectionUsername)) {
            env.put(Context.SECURITY_PRINCIPAL, connectionUsername);
        }
        if (connectionPassword != null || !"".equals(connectionPassword)) {
            env.put(Context.SECURITY_CREDENTIALS, connectionPassword);
        }
        env.put(Context.SECURITY_PROTOCOL, connectionProtocol == null ? "" : connectionProtocol);
        env.put(Context.PROVIDER_URL, connectionURL == null ? "" : connectionURL);
        env.put(Context.SECURITY_AUTHENTICATION, authentication == null ? "" : authentication);
        context = new InitialDirContext(env);

    } catch (NamingException e) {
        log.error(e);
        throw e;
    }
    return context;
}

From source file:org.apache.hadoop.security.authentication.server.LdapAuthenticationHandler.java

private void authenticateWithTlsExtension(String userDN, String password) throws AuthenticationException {
    LdapContext ctx = null;//from   w ww  . j  a  va  2 s.  c  o  m
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerUrl);

    try {
        // Create initial context
        ctx = new InitialLdapContext(env, null);
        // Establish TLS session
        StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());

        if (disableHostNameVerification) {
            tls.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }

        tls.negotiate();

        // Initialize security credentials & perform read operation for
        // verification.
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        ctx.lookup(userDN);
        logger.debug("Authentication successful for {}", userDN);

    } catch (NamingException | IOException ex) {
        throw new AuthenticationException("Error validating LDAP user", ex);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) { /* Ignore. */
            }
        }
    }
}

From source file:org.apache.hadoop.security.authentication.server.LdapAuthenticationHandler.java

private void authenticateWithoutTlsExtension(String userDN, String password) throws AuthenticationException {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, password);

    try {//from w w w .  ja  v a  2s. c  om
        // Create initial context
        Context ctx = new InitialDirContext(env);
        ctx.close();
        logger.debug("Authentication successful for {}", userDN);

    } catch (NamingException e) {
        throw new AuthenticationException("Error validating LDAP user", e);
    }
}

From source file:org.apache.hadoop.security.LdapGroupsMapping.java

DirContext getDirContext() throws NamingException {
    if (ctx == null) {
        // Set up the initial environment for LDAP connectivity
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, com.sun.jndi.ldap.LdapCtxFactory.class.getName());
        env.put(Context.PROVIDER_URL, ldapUrl);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        // Set up SSL security, if necessary
        if (useSsl) {
            env.put(Context.SECURITY_PROTOCOL, "ssl");
            System.setProperty("javax.net.ssl.keyStore", keystore);
            System.setProperty("javax.net.ssl.keyStorePassword", keystorePass);
        }//from   w  w  w  . j  a v  a  2s  .c  o  m

        env.put(Context.SECURITY_PRINCIPAL, bindUser);
        env.put(Context.SECURITY_CREDENTIALS, bindPassword);

        env.put("com.sun.jndi.ldap.connect.timeout",
                conf.get(CONNECTION_TIMEOUT, String.valueOf(CONNECTION_TIMEOUT_DEFAULT)));
        env.put("com.sun.jndi.ldap.read.timeout", conf.get(READ_TIMEOUT, String.valueOf(READ_TIMEOUT_DEFAULT)));

        ctx = new InitialDirContext(env);
    }

    return ctx;
}

From source file:org.apache.jackrabbit.oak.security.authentication.ldap.AbstractServer.java

/**
 * Common code to get an initial context via a simple bind to the
 * server over the wire using the SUN JNDI LDAP provider. Do not use
 * this method until after the setUp() method is called to start the
 * server otherwise it will fail.//ww  w .jav  a2s. c  om
 *
 * @param bindPrincipalDn the DN of the principal to bind as
 * @param password        the password of the bind principal
 * @return an LDAP context as the the administrator to the rootDSE
 * @throws NamingException if the server cannot be contacted
 */
protected LdapContext getWiredContext(String bindPrincipalDn, String password) throws Exception {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY);
    env.put(Context.PROVIDER_URL, "ldap://localhost:" + port);
    env.put(Context.SECURITY_PRINCIPAL, bindPrincipalDn);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    return new InitialLdapContext(env, null);
}

From source file:org.apache.jackrabbit.oak.security.authentication.ldap.AbstractServer.java

/**
 * Sets the contexts for this base class.  Values of user and password used to
 * set the respective JNDI properties.  These values can be overriden by the
 * overrides properties./*w  ww.  j  a  v  a2s . c om*/
 *
 * @param user   the username for authenticating as this user
 * @param passwd the password of the user
 * @throws NamingException if there is a failure of any kind
 */
protected void setContexts(String user, String passwd) throws Exception {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(DirectoryService.JNDI_KEY, directoryService);
    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, passwd);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
    setContexts(env);
}