Search in sources :

Example 6 with NamingEnumeration

use of javax.naming.NamingEnumeration in project Openfire by igniterealtime.

the class LdapUserProvider method loadUser.

@Override
public User loadUser(String username) throws UserNotFoundException {
    if (username.contains("@")) {
        if (!XMPPServer.getInstance().isLocal(new JID(username))) {
            throw new UserNotFoundException("Cannot load user of remote server: " + username);
        }
        username = username.substring(0, username.lastIndexOf("@"));
    }
    // Un-escape username.
    username = JID.unescapeNode(username);
    DirContext ctx = null;
    try {
        String userDN = manager.findUserDN(username);
        // Load record.
        String[] attributes = new String[] { manager.getUsernameField(), manager.getNameField(), manager.getEmailField(), "createTimestamp", "modifyTimestamp" };
        ctx = manager.getContext(manager.getUsersBaseDN(username));
        Attributes attrs = ctx.getAttributes(userDN, attributes);
        String name = null;
        Attribute nameField = attrs.get(manager.getNameField());
        if (nameField != null) {
            name = (String) nameField.get();
        }
        String email = null;
        Attribute emailField = attrs.get(manager.getEmailField());
        if (emailField != null) {
            email = (String) emailField.get();
        }
        Date creationDate = new Date();
        Attribute creationDateField = attrs.get("createTimestamp");
        if (creationDateField != null && "".equals(((String) creationDateField.get()).trim())) {
            creationDate = parseLDAPDate((String) creationDateField.get());
        }
        Date modificationDate = new Date();
        Attribute modificationDateField = attrs.get("modifyTimestamp");
        if (modificationDateField != null && "".equals(((String) modificationDateField.get()).trim())) {
            modificationDate = parseLDAPDate((String) modificationDateField.get());
        }
        // Escape the username so that it can be used as a JID.
        username = JID.escapeNode(username);
        // As defined by RFC5803.
        Attribute authPassword = attrs.get("authPassword");
        User user = new User(username, name, email, creationDate, modificationDate);
        if (authPassword != null) {
            // The authPassword attribute can be multivalued.
            // Not sure if this is the right API to loop through them.
            NamingEnumeration values = authPassword.getAll();
            while (values.hasMore()) {
                Attribute authPasswordValue = (Attribute) values.next();
                String[] parts = ((String) authPasswordValue.get()).split("$");
                String[] authInfo = parts[1].split(":");
                String[] authValue = parts[2].split(":");
                String scheme = parts[0].trim();
                // We only support SCRAM-SHA-1 at the moment.
                if ("SCRAM-SHA-1".equals(scheme)) {
                    int iterations = Integer.valueOf(authInfo[0].trim());
                    String salt = authInfo[1].trim();
                    String storedKey = authValue[0].trim();
                    String serverKey = authValue[1].trim();
                    user.setSalt(salt);
                    user.setStoredKey(storedKey);
                    user.setServerKey(serverKey);
                    user.setIterations(iterations);
                    break;
                }
            }
        }
        return user;
    } catch (Exception e) {
        throw new UserNotFoundException(e);
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (Exception ignored) {
        // Ignore.
        }
    }
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) User(org.jivesoftware.openfire.user.User) JID(org.xmpp.packet.JID) Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) NamingEnumeration(javax.naming.NamingEnumeration) DirContext(javax.naming.directory.DirContext) Date(java.util.Date) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException)

Example 7 with NamingEnumeration

use of javax.naming.NamingEnumeration in project neo4j by neo4j.

the class LdapRealmTest method shouldWarnAboutAmbiguousUserSearch.

@Test
public void shouldWarnAboutAmbiguousUserSearch() throws NamingException {
    when(config.get(SecuritySettings.ldap_authorization_user_search_filter)).thenReturn("{0}");
    LdapContext ldapContext = mock(LdapContext.class);
    NamingEnumeration result = mock(NamingEnumeration.class);
    SearchResult searchResult = mock(SearchResult.class);
    when(ldapContext.search(anyString(), anyString(), anyObject(), anyObject())).thenReturn(result);
    when(result.hasMoreElements()).thenReturn(true);
    when(result.next()).thenReturn(searchResult);
    when(searchResult.toString()).thenReturn("<ldap search result>");
    LdapRealm realm = new LdapRealm(config, securityLog, secureHasher);
    realm.findRoleNamesForUser("username", ldapContext);
    verify(securityLog).warn(contains("LDAP user search for user principal 'username' is ambiguous"));
}
Also used : NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult) LdapContext(javax.naming.ldap.LdapContext) Test(org.junit.Test)

Example 8 with NamingEnumeration

use of javax.naming.NamingEnumeration in project neo4j by neo4j.

the class LdapRealmTest method shouldWarnAboutUserSearchBaseBeingEmpty.

@Test
public void shouldWarnAboutUserSearchBaseBeingEmpty() throws Exception {
    when(config.get(SecuritySettings.ldap_authorization_user_search_base)).thenReturn("");
    LdapContext ldapContext = mock(LdapContext.class);
    NamingEnumeration result = mock(NamingEnumeration.class);
    when(ldapContext.search(anyString(), anyString(), anyObject(), anyObject())).thenReturn(result);
    when(result.hasMoreElements()).thenReturn(false);
    assertException(this::makeAndInit, IllegalArgumentException.class, "Illegal LDAP user search settings, see security log for details.");
    verify(securityLog).error(contains("LDAP user search base is empty."));
}
Also used : NamingEnumeration(javax.naming.NamingEnumeration) LdapContext(javax.naming.ldap.LdapContext) Test(org.junit.Test)

Example 9 with NamingEnumeration

use of javax.naming.NamingEnumeration in project platformlayer by platformlayer.

the class ITOpenLdapService method testLdap.

private void testLdap(String ldapUrl, Secret adminPassword) throws NamingException {
    Hashtable<String, String> env = new Hashtable<String, String>();
    String sp = "com.sun.jndi.ldap.LdapCtxFactory";
    env.put(Context.INITIAL_CONTEXT_FACTORY, sp);
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "cn=Manager,dc=test,dc=platformlayer,dc=org");
    env.put(Context.SECURITY_CREDENTIALS, adminPassword.plaintext());
    DirContext ctx = new InitialDirContext(env);
    NamingEnumeration results = ctx.list("dc=test,dc=platformlayer,dc=org");
    while (results.hasMore()) {
        NameClassPair sr = (NameClassPair) results.next();
        System.out.println(sr.getNameInNamespace());
    }
    ctx.close();
}
Also used : Hashtable(java.util.Hashtable) NameClassPair(javax.naming.NameClassPair) NamingEnumeration(javax.naming.NamingEnumeration) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 10 with NamingEnumeration

use of javax.naming.NamingEnumeration in project spring-security by spring-projects.

the class PasswordComparisonAuthenticatorMockTests method ldapCompareOperationIsUsedWhenPasswordIsNotRetrieved.

// ~ Methods
// ========================================================================================================
@Test
public void ldapCompareOperationIsUsedWhenPasswordIsNotRetrieved() throws Exception {
    final DirContext dirCtx = mock(DirContext.class);
    final BaseLdapPathContextSource source = mock(BaseLdapPathContextSource.class);
    final BasicAttributes attrs = new BasicAttributes();
    attrs.put(new BasicAttribute("uid", "bob"));
    PasswordComparisonAuthenticator authenticator = new PasswordComparisonAuthenticator(source);
    authenticator.setUserDnPatterns(new String[] { "cn={0},ou=people" });
    // Get the mock to return an empty attribute set
    when(source.getReadOnlyContext()).thenReturn(dirCtx);
    when(dirCtx.getAttributes(eq("cn=Bob,ou=people"), any(String[].class))).thenReturn(attrs);
    when(dirCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org");
    // Setup a single return value (i.e. success)
    final NamingEnumeration searchResults = new BasicAttributes("", null).getAll();
    when(dirCtx.search(eq("cn=Bob,ou=people"), eq("(userPassword={0})"), any(Object[].class), any(SearchControls.class))).thenReturn(searchResults);
    authenticator.authenticate(new UsernamePasswordAuthenticationToken("Bob", "bobspassword"));
}
Also used : BasicAttribute(javax.naming.directory.BasicAttribute) BasicAttributes(javax.naming.directory.BasicAttributes) BaseLdapPathContextSource(org.springframework.ldap.core.support.BaseLdapPathContextSource) NamingEnumeration(javax.naming.NamingEnumeration) SearchControls(javax.naming.directory.SearchControls) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) DirContext(javax.naming.directory.DirContext) Test(org.junit.Test)

Aggregations

NamingEnumeration (javax.naming.NamingEnumeration)48 Attribute (javax.naming.directory.Attribute)22 SearchResult (javax.naming.directory.SearchResult)20 NamingException (javax.naming.NamingException)19 Attributes (javax.naming.directory.Attributes)19 SearchControls (javax.naming.directory.SearchControls)18 DirContext (javax.naming.directory.DirContext)14 ArrayList (java.util.ArrayList)11 LdapContext (javax.naming.ldap.LdapContext)10 Test (org.junit.Test)9 InitialContext (javax.naming.InitialContext)7 Hashtable (java.util.Hashtable)6 Context (javax.naming.Context)6 InitialDirContext (javax.naming.directory.InitialDirContext)6 HashMap (java.util.HashMap)5 IOException (java.io.IOException)3 HashSet (java.util.HashSet)3 Binding (javax.naming.Binding)3 NameClassPair (javax.naming.NameClassPair)3 NameNotFoundException (javax.naming.NameNotFoundException)3