Example usage for javax.naming Context SECURITY_PRINCIPAL

List of usage examples for javax.naming Context SECURITY_PRINCIPAL

Introduction

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

Prototype

String SECURITY_PRINCIPAL

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

Click Source Link

Document

Constant that holds the name of the environment property for specifying the identity of the principal for authenticating the caller to the service.

Usage

From source file:xc.mst.manager.user.DefaultUserService.java

/**
 * Creates a connection to the LDAP server based on values defined in the configuration file.
 * This method logs into the server with a specified username and password
 * //from  ww w.  j a  v  a 2s .c  om
 * @param username
 *            The username to log into the LDAP server
 * @param password
 *            The password to log into the LDAP server
 * @return A connection to the LDAP server defined in the configuration file.
 * @throws ILSException
 *             if the username and password were wrong or we couldn't find the LDAP server
 */
private static DirContext getLDAPConnection(String username, String password, Server loginserver) {

    Properties ldapProperties = getGenericLDAPProperties(loginserver);
    try {
        // Set up the environment for creating the initial context

        // Get the username attribute and start location on the LDAP server from the configuration file
        String usernameAttribute = loginserver.getUserNameAttribute();
        String startLocation = loginserver.getStartLocation();

        // Set up the properties to authenticate with the correct username and password
        // The username passed to this function will be something like "jsmith", but we
        // need to authenticate to the correct LDAP location using the provided parameter.
        // For this reason we pull the username attribute at start locations from the
        // configuration file. The result will be setting the SECURITY_PRINCIPAL (LDAP username)
        // to something like "uid=jsmith, ou=people, dc=rochester, dc=edu"
        ldapProperties.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); // Set this property because we will be authenticating
        ldapProperties.setProperty(Context.SECURITY_PRINCIPAL,
                usernameAttribute + "=" + username + ", " + startLocation);
        ldapProperties.setProperty(Context.SECURITY_CREDENTIALS, password);

        // Get the environment properties (props) for creating initial
        // context and specifying LDAP service provider parameters.
        return new InitialDirContext(ldapProperties);
    }
    // catch(MalformedURLException e1) {} // not thrown in above, but I thought I saw this in the log with misconfigured ldap?
    // catch(AuthenticationException e2) {} // more specific then below, I think this is the one thrown if invalid password.
    catch (NamingException e) {
        // If the exception was an error code 49, the username or password was incorrect.
        log.error(
                "Exception occured while authenticating user against LDAP server.If the exception was an error code 49, the username or password was incorrect",
                e);
        InitialDirContext in = null;
        return in;
    }
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java

/**
 * @throws NoSuchElementException if no user could be found with the given login
 * @throws AuthenticationException if the password does not match
 * @throws CommunicationException e.g. on server timeout
 * @throws NamingException on any other LDAP error
 *///from   ww  w .j  ava 2  s .  c o  m
private HashMap<String, String> auth(String login, String password) throws NamingException {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put("com.sun.jndi.ldap.read.timeout", timeout);
    env.put("com.sun.jndi.ldap.connect.timeout", connectTimeout);
    if (binddn != null) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, binddn);
        env.put(Context.SECURITY_CREDENTIALS, bindpw);
    }

    HashMap<String, String> userAttrs = new HashMap<String, String>();
    String uid;

    DirContext ctx = new InitialDirContext(env);
    try {
        uid = searchUser(login, userAttrs, ctx);
    } finally {
        ctx.close();
    }

    if (passwordAttribute != null) {
        if (!userAttrs.containsKey("_pass"))
            throw new NoSuchElementException();
        String pass = userAttrs.get("_pass");
        if (pass == null || !pass.startsWith("{x-plain}"))
            throw new NoSuchElementException();
        log.debug("found password");
        pass = pass.substring(9);
        if (!pass.equals(password))
            throw new NoSuchElementException();
        userAttrs.remove("_pass");
    } else {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, uid + "," + base);
        env.put(Context.SECURITY_CREDENTIALS, password);
        DirContext ctx2 = new InitialDirContext(env);
        try {
            if (readAttributesAsSelf)
                searchUser(login, userAttrs, ctx2);
        } finally {
            ctx2.close();
        }
    }
    return userAttrs;
}

From source file:org.olat.ldap.LDAPLoginManagerImpl.java

/**
 * Connect to the LDAP server with System DN and Password Configuration: LDAP URL = olatextconfig.xml (property=ldapURL) System DN = olatextconfig.xml
 * (property=ldapSystemDN) System PW = olatextconfig.xml (property=ldapSystemPW)
 * //from   w ww.  ja va 2s. c  o m
 * @return The LDAP connection (LdapContext) or NULL if connect fails
 * @throws NamingException
 */
public LdapContext bindSystem() {
    // set LDAP connection attributes
    final Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAPLoginModule.getLdapUrl());
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, LDAPLoginModule.getLdapSystemDN());
    env.put(Context.SECURITY_CREDENTIALS, LDAPLoginModule.getLdapSystemPW());

    // check ssl
    if (LDAPLoginModule.isSslEnabled()) {
        enableSSL(env);
    }

    try {
        final InitialLdapContext ctx = new InitialLdapContext(env, new Control[] {});
        ctx.getConnectControls();
        return ctx;
    } catch (final NamingException e) {
        logError("NamingException when trying to bind system with DN::" + LDAPLoginModule.getLdapSystemDN()
                + " and PW::" + LDAPLoginModule.getLdapSystemPW() + " on URL::" + LDAPLoginModule.getLdapUrl(),
                e);
        return null;
    } catch (final Exception e) {
        logError("Exception when trying to bind system with DN::" + LDAPLoginModule.getLdapSystemDN()
                + " and PW::" + LDAPLoginModule.getLdapSystemPW() + " on URL::" + LDAPLoginModule.getLdapUrl(),
                e);
        return null;
    }

}

From source file:com.wfp.utils.LDAPUtils.java

/**
 * Overloaded method for getting the LDAP COntext based on the host,username, password
 * @param host/*from w  w w.  jav  a  2  s.  c o m*/
 * @param adminName
 * @param adminPassword
 * @return
 * @throws NamingException
 */
@SuppressWarnings("unchecked")
public static LdapContext getLDAPContext(String host, String adminName, String adminPassword)
        throws NamingException {
    //Logger.info("Creating LDAP Context", LDAPUtils.class);
    Hashtable props = System.getProperties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.SECURITY_AUTHENTICATION, LDAP_SECURITY_AUTHENTICATION);
    props.put(Context.SECURITY_PRINCIPAL, adminName);
    props.put(Context.SECURITY_CREDENTIALS, adminPassword);
    props.put(Context.PROVIDER_URL, host);
    if (!StringUtils.isNull(LDAPConfigUtils.getTrustStorePath())) {
        System.setProperty("javax.net.ssl.trustStore", LDAPConfigUtils.getTrustStorePath());
        props.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    //Logger.info("Completed creating LDAP Context for host ["+host+"]", LDAPUtils.class);
    return (new InitialLdapContext(props, null));
}

From source file:org.webterm.core.plugin.authentication.LdapAuthentication.java

@Override
public void init() {
    LOG.info("Initializing LDAP authentication..."); //$NON-NLS-1$

    try {//from  w ww . ja  v  a2  s . c o m
        final ConfigurationReader config = ConfigurationReader.getInstance();
        final String serverName = config.getApplicationProperty(CONFIG_SERVER_NAME);
        final String serverPort = config.getApplicationProperty(CONFIG_SERVER_PORT);
        final String bindDn = config.getApplicationProperty(CONFIG_BIND_DN);
        final String bindPwd = config.getApplicationProperty(CONFIG_BIND_PWD);
        this.baseDn = config.getApplicationProperty(CONFIG_BASE_DN);
        this.attrUser = config.getApplicationProperty(CONFIG_ATTR_USER);
        this.attrPwd = config.getApplicationProperty(CONFIG_ATTR_PWD);
        this.checkMethode = this.map.get(config.getApplicationProperty(CONFIG_PASSWORD_ENCODE));
        if (this.checkMethode == null) {
            LOG.fatal("unknown method: " + config.getApplicationProperty(CONFIG_PASSWORD_ENCODE)); //$NON-NLS-1$
        }

        final Hashtable<String, String> ldapEnv = new Hashtable<String, String>(); // NOPMD - HashTable is needed
        ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); //$NON-NLS-1$
        ldapEnv.put(Context.PROVIDER_URL, "ldap://" + serverName + ":" + serverPort); //$NON-NLS-1$ //$NON-NLS-2$
        ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");//$NON-NLS-1$
        ldapEnv.put(Context.SECURITY_PRINCIPAL, bindDn);
        ldapEnv.put(Context.SECURITY_CREDENTIALS, bindPwd);
        this.ldapContext = new InitialDirContext(ldapEnv);
    } catch (Exception ex) {
        LOG.error(ex, ex);
    }
}

From source file:org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl.java

private InitialDirContext buildInitialDirContext(Hashtable<String, String> env, int pageSize,
        AuthenticationDiagnostic diagnostic) throws AuthenticationException {
    String securityPrincipal = env.get(Context.SECURITY_PRINCIPAL);
    String providerURL = env.get(Context.PROVIDER_URL);

    if (isSSLSocketFactoryRequired()) {
        KeyStore trustStore = initTrustStore();
        AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName());
    }/*from w ww.  j  ava 2 s .  com*/

    if (diagnostic == null) {
        diagnostic = new AuthenticationDiagnostic();
    }
    try {
        // If a page size has been requested, use LDAP v3 paging
        if (pageSize > 0) {
            InitialLdapContext ctx = new InitialLdapContext(env, null);
            ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });
            return ctx;
        } else {
            InitialDirContext ret = new InitialDirContext(env);
            Object[] args = { providerURL, securityPrincipal };
            diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
            return ret;
        }
    } catch (javax.naming.AuthenticationException ax) {
        Object[] args1 = { securityPrincipal };
        Object[] args = { providerURL, securityPrincipal };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_AUTHENTICATION, false, args1);

        // wrong user/password - if we get this far the connection is O.K
        Object[] args2 = { securityPrincipal, ax.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.authentication", diagnostic, args2, ax);
    } catch (CommunicationException ce) {
        Object[] args1 = { providerURL };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args1);

        StringBuffer message = new StringBuffer();

        message.append(ce.getClass().getName() + ", " + ce.getMessage());

        Throwable cause = ce.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        // failed to connect
        Object[] args = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.communication", diagnostic, args, cause);
    } catch (NamingException nx) {
        Object[] args = { providerURL };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args);

        StringBuffer message = new StringBuffer();

        message.append(nx.getClass().getName() + ", " + nx.getMessage());

        Throwable cause = nx.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        // failed to connect
        Object[] args1 = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.connection", diagnostic, args1, nx);
    } catch (IOException e) {
        Object[] args = { providerURL, securityPrincipal };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);

        throw new AuthenticationException("Unable to encode LDAP v3 request controls", e);
    }
}

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.//from   www  .j  a v a2  s  . c o m
 *
 * @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.jboss.test.security.test.SubjectContextUnitTestCase.java

public void testGroupMemberMethod() throws Exception {
    log.debug("+++ testGroupMemberMethod()");
    Properties env = new Properties();
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.security.jndi.JndiLoginInitialContextFactory");
    env.setProperty(Context.SECURITY_PRINCIPAL, "jduke");
    env.setProperty(Context.SECURITY_CREDENTIALS, "theduke");
    InitialContext ctx = new InitialContext(env);
    Object obj = ctx.lookup("jacc/Secured");
    obj = PortableRemoteObject.narrow(obj, SecuredServiceRemoteHome.class);
    SecuredServiceRemoteHome home = (SecuredServiceRemoteHome) obj;
    log.debug("Found SecuredServiceRemoteHome");
    SecuredServiceRemote bean = home.create();
    log.debug("Created SecuredServiceRemote");

    Principal callerIdentity = new SimplePrincipal("jduke");
    Principal runAsIdentity = new SimplePrincipal("runAsUser");
    HashSet expectedCallerRoles = new HashSet();
    expectedCallerRoles.add("groupMemberCaller");
    expectedCallerRoles.add("userCaller");
    expectedCallerRoles.add("allAuthCaller");
    expectedCallerRoles.add("webUser");
    HashSet expectedRunAsRoles = new HashSet();
    expectedRunAsRoles.add("identitySubstitutionCaller");
    expectedRunAsRoles.add("extraRunAsRole");
    CallerInfo info = new CallerInfo(callerIdentity, runAsIdentity, expectedCallerRoles, expectedRunAsRoles);
    bean.groupMemberMethod(info);//w w w  . j a va 2  s  .c om
    bean.remove();
}

From source file:com.evolveum.midpoint.pwdfilter.opendj.PasswordPusher.java

private void readConfig() throws InitializationException {

    String configFile = "/opt/midpoint/opendj-pwdpusher.xml";
    if (System.getProperty("config") != null) {
        configFile = System.getProperty("config");
    }/*w w  w .  jav  a2 s. c  om*/

    File f = new File(configFile);
    if (!f.exists() || !f.canRead()) {
        throw new IllegalArgumentException("Config file " + configFile + " does not exist or is not readable");
    }

    try {
        XMLConfiguration config = new XMLConfiguration(f);

        String notifierDN = "cn=" + config.getString("passwordpusher.statusNotifierName")
                + ",cn=Account Status Notification Handlers";
        String ldapURL = config.getString("passwordpusher.ldapServerURL");
        boolean ldapSSL = config.getBoolean("passwordpusher.ldapServerSSL");
        String ldapUsername = config.getString("passwordpusher.ldapServerUsername");
        String ldapPassword = config.getString("passwordpusher.ldapServerPassword");

        Hashtable<Object, Object> env = new Hashtable<Object, Object>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldapURL + "/cn=config");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, ldapUsername);
        env.put(Context.SECURITY_CREDENTIALS, ldapPassword);

        if (ldapSSL) {
            env.put(Context.SECURITY_PROTOCOL, "ssl");
        }

        try {
            DirContext context = new InitialDirContext(env);
            Attributes attr = context.getAttributes(notifierDN);

            this.endPoint = attr.get("ds-cfg-referrals-url").get(0).toString();
            this.username = attr.get("ds-cfg-midpoint-username").get(0).toString();
            this.password = attr.get("ds-cfg-midpoint-password").get(0).toString();
            this.pwdChangeDirectory = attr.get("ds-cfg-midpoint-passwordcachedir").get(0).toString();
        } catch (NamingException ne) {
            throw new InitializationException(
                    ERR_MIDPOINT_PWDSYNC_READING_CONFIG_FROM_LDAP.get(ne.getMessage()), ne);
        }
    } catch (ConfigurationException ce) {
        throw new InitializationException(ERR_MIDPOINT_PWDSYNC_PARSING_XML_CONFIG.get(ce.getMessage()), ce);
    }
}

From source file:org.mule.providers.ldap.util.DSManager.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./*  www.  j a  v  a2  s .co  m*/
 * 
 * @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 NamingException {
    Hashtable env = new Hashtable(configuration.toJndiEnvironment());
    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, passwd);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.INITIAL_CONTEXT_FACTORY, ServerContextFactory.class.getName());
    setContexts(env);
}