Search in sources :

Example 61 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project alfresco-repository by Alfresco.

the class LDAPInitialDirContextFactoryImpl method main.

public static void main(String[] args) {
    // ....build a pyramid selling scheme .....
    // A group has three user members and 2 group members .... and off we go ....
    // We make the people and groups to represent this and stick them into LDAP ...used to populate a test data base for user and groups
    int userMembers = Integer.parseInt(args[3]);
    ApplicationContext applicationContext = ApplicationContextHelper.getApplicationContext();
    LDAPInitialDirContextFactory factory = (LDAPInitialDirContextFactory) applicationContext.getBean("ldapInitialDirContextFactory");
    InitialDirContext ctx = null;
    try {
        ctx = factory.getInitialDirContext("cn=" + args[0] + "," + args[2], args[1]);
        /* Values we'll use in creating the entry */
        Attribute objClasses = new BasicAttribute("objectclass");
        objClasses.add("top");
        objClasses.add("person");
        objClasses.add("organizationalPerson");
        objClasses.add("inetOrgPerson");
        for (int i = 0; i < userMembers; i++) {
            Attribute cn = new BasicAttribute("cn", "User" + i + " TestUser");
            Attribute sn = new BasicAttribute("sn", "TestUser");
            Attribute givenNames = new BasicAttribute("givenName", "User" + i);
            Attribute telephoneNumber = new BasicAttribute("telephoneNumber", "123");
            Attribute uid = new BasicAttribute("uid", "User" + i);
            Attribute mail = new BasicAttribute("mail", "woof@woof");
            Attribute o = new BasicAttribute("o", "Alfresco");
            Attribute userPassword = new BasicAttribute("userPassword", "bobbins");
            /* Specify the DN we're adding */
            String dn = "cn=User" + i + " TestUser," + args[2];
            Attributes orig = new BasicAttributes();
            orig.put(objClasses);
            orig.put(cn);
            orig.put(sn);
            orig.put(givenNames);
            orig.put(telephoneNumber);
            orig.put(uid);
            orig.put(mail);
            orig.put(o);
            orig.put(userPassword);
            try {
                ctx.destroySubcontext(dn);
            } catch (NamingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ctx.createSubcontext(dn, orig);
        }
    } catch (NamingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : BasicAttribute(javax.naming.directory.BasicAttribute) BasicAttributes(javax.naming.directory.BasicAttributes) ApplicationContext(org.springframework.context.ApplicationContext) BasicAttribute(javax.naming.directory.BasicAttribute) Attribute(javax.naming.directory.Attribute) BasicAttributes(javax.naming.directory.BasicAttributes) Attributes(javax.naming.directory.Attributes) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 62 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project alfresco-repository by Alfresco.

the class ChainingUserRegistrySynchronizerTest method getMockedLDAPSearchResult.

private LDAPInitialDirContextFactoryImpl getMockedLDAPSearchResult(boolean withEmail) throws NamingException {
    @SuppressWarnings("unchecked") NamingEnumeration<SearchResult> mockedNamingEnumeration = mock(NamingEnumeration.class);
    when(mockedNamingEnumeration.hasMore()).thenReturn(true).thenReturn(false);
    BasicAttributes attributes = new BasicAttributes();
    attributes.put(new BasicAttribute("sAMAccountName", "U1"));
    attributes.put(new BasicAttribute("givenName", "U1"));
    if (withEmail) {
        attributes.put(new BasicAttribute("mail", "U1@alfresco.com"));
    }
    SearchResult mockedSearchResult = new SearchResult("CN:U1", null, attributes);
    mockedSearchResult.setNameInNamespace("CN:U1");
    when(mockedNamingEnumeration.next()).thenReturn(mockedSearchResult);
    InitialDirContext mockedInitialDirContext = mock(InitialDirContext.class);
    when(mockedInitialDirContext.search((String) any(), anyString(), any(SearchControls.class))).thenReturn(mockedNamingEnumeration);
    LDAPInitialDirContextFactoryImpl mockedLdapInitialDirContextFactory = mock(LDAPInitialDirContextFactoryImpl.class);
    when(mockedLdapInitialDirContextFactory.getDefaultIntialDirContext(0)).thenReturn(mockedInitialDirContext);
    return mockedLdapInitialDirContextFactory;
}
Also used : BasicAttribute(javax.naming.directory.BasicAttribute) BasicAttributes(javax.naming.directory.BasicAttributes) SearchResult(javax.naming.directory.SearchResult) SearchControls(javax.naming.directory.SearchControls) InitialDirContext(javax.naming.directory.InitialDirContext) LDAPInitialDirContextFactoryImpl(org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl)

Example 63 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project alfresco-repository by Alfresco.

the class LDAPUserRegistry method resolveDistinguishedName.

/*
     * (non-Javadoc)
     * @see org.alfresco.repo.security.sync.ldap.LDAPNameResolver#resolveDistinguishedName(java.lang.String)
     */
public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic) throws AuthenticationException {
    if (logger.isDebugEnabled()) {
        logger.debug("resolveDistinguishedName userId:" + userId);
    }
    SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868
    userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName });
    String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))";
    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;
    InitialDirContext ctx = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic);
        // Execute the user query with an additional condition that ensures only the user with the required ID is
        // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation
        searchResults = ctx.search(this.userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls);
        if (searchResults.hasMore()) {
            result = searchResults.next();
            Attributes attributes = result.getAttributes();
            Attribute uidAttribute = attributes.get(this.userIdAttributeName);
            if (uidAttribute == null) {
                if (this.errorOnMissingUID) {
                    throw new AlfrescoRuntimeException("User returned by user search does not have mandatory user id attribute " + attributes);
                } else {
                    LDAPUserRegistry.logger.warn("User returned by user search does not have mandatory user id attribute " + attributes);
                }
            } else // only resolve this user if the user ID matches
            if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) {
                String name = result.getNameInNamespace();
                // Close the contexts, see ALF-20682
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
                result = null;
                return name;
            }
            // Close the contexts, see ALF-20682
            Context context = (Context) result.getObject();
            if (context != null) {
                context.close();
            }
            result = null;
        }
        Object[] args = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args);
        throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic);
    } catch (NamingException e) {
        // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory
        Object[] args1 = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1);
        // failed to search
        Object[] args = { e.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e);
    } finally {
        if (result != null) {
            try {
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
            } catch (Exception e) {
                logger.debug("error when closing result block context", e);
            }
        }
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (Exception e) {
                logger.debug("error when closing searchResults context", e);
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                logger.debug("error when closing ldap context", e);
            }
        }
    }
}
Also used : LdapContext(javax.naming.ldap.LdapContext) InitialDirContext(javax.naming.directory.InitialDirContext) Context(javax.naming.Context) DirContext(javax.naming.directory.DirContext) Attribute(javax.naming.directory.Attribute) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) InitialDirContext(javax.naming.directory.InitialDirContext) NamingException(javax.naming.NamingException) ParseException(java.text.ParseException) ServiceUnavailableException(javax.naming.ServiceUnavailableException) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) InvalidNameException(javax.naming.InvalidNameException) CommunicationException(javax.naming.CommunicationException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException)

Example 64 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project karaf by apache.

the class LdapPoolingTest method testSSLConnectionWithoutPool.

@Test
public void testSSLConnectionWithoutPool() throws Exception {
    System.setProperty("com.sun.jndi.ldap.connect.pool.maxsize", "2");
    System.setProperty("com.sun.jndi.ldap.connect.pool.protocol", "ssl");
    System.setProperty("com.sun.jndi.ldap.connect.pool.debug", "all");
    Hashtable<String, String> env = new Hashtable<>();
    env.put("com.sun.jndi.ldap.connect.pool", "false");
    env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
    env.put("java.naming.provider.url", "ldaps://localhost:" + getLdapServer().getPortSSL() + "/ou=system");
    env.put("java.naming.ldap.factory.socket", ManagedSSLSocketFactory.class.getName());
    env.put("java.naming.security.protocol", "ssl");
    env.put("java.naming.security.principal", "uid=admin,ou=system");
    env.put("java.naming.security.credentials", "secret");
    env.put("java.naming.security.authentication", "simple");
    final int[] socketsCreated = new int[] { 0 };
    ManagedSSLSocketFactory.setSocketFactory(new ManagedSSLSocketFactory(sslContext.getSocketFactory()) {

        @Override
        public Socket createSocket() throws IOException {
            socketsCreated[0]++;
            return super.createSocket();
        }

        @Override
        public Socket createSocket(String host, int port) throws IOException {
            socketsCreated[0]++;
            return super.createSocket(host, port);
        }
    });
    InitialDirContext context = new InitialDirContext(env);
    context.close();
    new InitialDirContext(env);
    context.close();
    ManagedSSLSocketFactory.setSocketFactory(null);
    assertThat(socketsCreated[0], equalTo(2));
}
Also used : Hashtable(java.util.Hashtable) IOException(java.io.IOException) InitialDirContext(javax.naming.directory.InitialDirContext) Socket(java.net.Socket) Test(org.junit.Test)

Example 65 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project iaf by ibissource.

the class LdapClient method checkPassword.

public String checkPassword(String userDN, String password, String baseDN, String returnedAttribute) throws NamingException {
    if (userDN == null || userDN.equals("") || password == null || password.equals("")) {
        return null;
    }
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.putAll(jndiEnv);
    env.put("com.sun.jndi.ldap.connect.pool", "false");
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, password);
    // initiate private context, to avoid pooling of authentication
    InitialDirContext context = new InitialDirContext(env);
    try {
        return searchObjectForSingleAttribute(context, userDN, baseDN, returnedAttribute);
    } finally {
        context.close();
    }
}
Also used : Hashtable(java.util.Hashtable) InitialDirContext(javax.naming.directory.InitialDirContext)

Aggregations

InitialDirContext (javax.naming.directory.InitialDirContext)131 DirContext (javax.naming.directory.DirContext)71 NamingException (javax.naming.NamingException)67 Hashtable (java.util.Hashtable)51 Attributes (javax.naming.directory.Attributes)34 Attribute (javax.naming.directory.Attribute)24 SearchResult (javax.naming.directory.SearchResult)22 SearchControls (javax.naming.directory.SearchControls)19 IOException (java.io.IOException)11 CommunicationException (javax.naming.CommunicationException)11 Test (org.junit.Test)11 Properties (java.util.Properties)10 BasicAttributes (javax.naming.directory.BasicAttributes)9 ArrayList (java.util.ArrayList)8 LoginException (javax.security.auth.login.LoginException)8 NameClassPair (javax.naming.NameClassPair)7 HashSet (java.util.HashSet)6 NamingEnumeration (javax.naming.NamingEnumeration)6 BasicAttribute (javax.naming.directory.BasicAttribute)6 ResultCodeException (eu.bcvsolutions.idm.core.api.exception.ResultCodeException)5