Search in sources :

Example 61 with DirContext

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

the class ActiveDirectoryLdapAuthenticationProviderTests method noUserSearchCausesUsernameNotFound.

// SEC-2017
@Test(expected = BadCredentialsException.class)
public void noUserSearchCausesUsernameNotFound() throws Exception {
    DirContext ctx = mock(DirContext.class);
    when(ctx.getNameInNamespace()).thenReturn("");
    when(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class))).thenReturn(new EmptyEnumeration<SearchResult>());
    provider.contextFactory = createContextFactoryReturning(ctx);
    provider.authenticate(joe);
}
Also used : SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) DirContext(javax.naming.directory.DirContext) Name(javax.naming.Name) DistinguishedName(org.springframework.ldap.core.DistinguishedName) Test(org.junit.Test)

Example 62 with DirContext

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

the class ActiveDirectoryLdapAuthenticationProviderTests method nullDomainIsSupportedIfAuthenticatingWithFullUserPrincipal.

@Test
public void nullDomainIsSupportedIfAuthenticatingWithFullUserPrincipal() throws Exception {
    provider = new ActiveDirectoryLdapAuthenticationProvider(null, "ldap://192.168.1.200/");
    DirContext ctx = mock(DirContext.class);
    when(ctx.getNameInNamespace()).thenReturn("");
    DirContextAdapter dca = new DirContextAdapter();
    SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
    when(ctx.search(eq(new DistinguishedName("DC=mydomain,DC=eu")), any(String.class), any(Object[].class), any(SearchControls.class))).thenReturn(new MockNamingEnumeration(sr));
    provider.contextFactory = createContextFactoryReturning(ctx);
    try {
        provider.authenticate(joe);
        fail("Expected BadCredentialsException for user with no domain information");
    } catch (BadCredentialsException expected) {
    }
    provider.authenticate(new UsernamePasswordAuthenticationToken("joe@mydomain.eu", "password"));
}
Also used : DistinguishedName(org.springframework.ldap.core.DistinguishedName) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) SearchResult(javax.naming.directory.SearchResult) SearchControls(javax.naming.directory.SearchControls) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) DirContext(javax.naming.directory.DirContext) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.Test)

Example 63 with DirContext

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

the class ActiveDirectoryLdapAuthenticationProviderTests method checkAuthentication.

private void checkAuthentication(String rootDn, ActiveDirectoryLdapAuthenticationProvider provider) throws NamingException {
    DirContext ctx = mock(DirContext.class);
    when(ctx.getNameInNamespace()).thenReturn("");
    DirContextAdapter dca = new DirContextAdapter();
    SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
    @SuppressWarnings("deprecation") DistinguishedName searchBaseDn = new DistinguishedName(rootDn);
    when(ctx.search(eq(searchBaseDn), any(String.class), any(Object[].class), any(SearchControls.class))).thenReturn(new MockNamingEnumeration(sr)).thenReturn(new MockNamingEnumeration(sr));
    provider.contextFactory = createContextFactoryReturning(ctx);
    Authentication result = provider.authenticate(joe);
    assertThat(result.getAuthorities()).isEmpty();
    dca.addAttributeValue("memberOf", "CN=Admin,CN=Users,DC=mydomain,DC=eu");
    result = provider.authenticate(joe);
    assertThat(result.getAuthorities()).hasSize(1);
}
Also used : DistinguishedName(org.springframework.ldap.core.DistinguishedName) Authentication(org.springframework.security.core.Authentication) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) SearchResult(javax.naming.directory.SearchResult) DirContext(javax.naming.directory.DirContext)

Example 64 with DirContext

use of javax.naming.directory.DirContext in project OpenAM by OpenRock.

the class Step4 method getLdapHostAndPort.

// Method to get hostname and port number with the
// provided Domain Name for Active Directory user data store.
private String[] getLdapHostAndPort(String domainName) throws NamingException, IOException {
    if (!domainName.endsWith(".")) {
        domainName += '.';
    }
    DirContext ictx = null;
    // The resource record type A is defined in RFC 1035. 
    try {
        Hashtable env = new Hashtable();
        env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        ictx = new InitialDirContext(env);
        Attributes attributes = ictx.getAttributes(domainName, new String[] { "A" });
        Attribute attrib = attributes.get("A");
        if (attrib == null) {
            throw new NamingException();
        }
    } catch (NamingException e) {
        // throw exception.
        throw e;
    }
    // then look for the LDAP server
    String serverHostName = null;
    String serverPortStr = null;
    final String ldapServer = "_ldap._tcp." + domainName;
    try {
        // Attempting to resolve ldapServer to SRV record.
        // This is a mechanism defined in MSDN, querying 
        // SRV records for _ldap._tcp.DOMAINNAME.
        // and get host and port from domain.
        Attributes attributes = ictx.getAttributes(ldapServer, new String[] { "SRV" });
        Attribute attr = attributes.get("SRV");
        if (attr == null) {
            throw new NamingException();
        }
        String[] srv = attr.get().toString().split(" ");
        String hostNam = srv[3];
        serverHostName = hostNam.substring(0, hostNam.length() - 1);
        if ((serverHostName != null) && serverHostName.length() > 0) {
            getContext().setSessionAttribute(SessionAttributeNames.USER_STORE_HOST, serverHostName);
        }
        serverPortStr = srv[2];
    } catch (NamingException e) {
        // throw exception.
        throw e;
    }
    // try to connect to LDAP port to make sure this machine 
    // has LDAP service
    int serverPort = Integer.parseInt(serverPortStr);
    if ((serverPort > 0) && (serverPort < 65535)) {
        getContext().setSessionAttribute(SessionAttributeNames.USER_STORE_PORT, serverPortStr);
    }
    try {
        new Socket(serverHostName, serverPort).close();
    } catch (IOException e) {
        throw e;
    }
    String[] hostAndPort = new String[2];
    hostAndPort[0] = serverHostName;
    hostAndPort[1] = serverPortStr;
    return hostAndPort;
}
Also used : Attribute(javax.naming.directory.Attribute) Hashtable(java.util.Hashtable) Attributes(javax.naming.directory.Attributes) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext) IOException(java.io.IOException) Socket(java.net.Socket)

Example 65 with DirContext

use of javax.naming.directory.DirContext in project uPortal by Jasig.

the class LDAPGroupStore method searchForEntities.

public EntityIdentifier[] searchForEntities(String query, int method, Class type) throws GroupsException {
    if (type != group && type != iperson)
        return new EntityIdentifier[0];
    // Guarantee that LDAP injection is prevented by replacing LDAP special characters
    // with escaped versions of the character
    query = LdapEncoder.filterEncode(query);
    ArrayList ids = new ArrayList();
    switch(method) {
        case STARTS_WITH:
            query = query + "*";
            break;
        case ENDS_WITH:
            query = "*" + query;
            break;
        case CONTAINS:
            query = "*" + query + "*";
            break;
    }
    query = namefield + "=" + query;
    DirContext context = getConnection();
    NamingEnumeration userlist = null;
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { keyfield });
    try {
        userlist = context.search(usercontext, query, sc);
        ArrayList keys = new ArrayList();
        processLdapResults(userlist, keys);
        String[] k = (String[]) keys.toArray(new String[0]);
        for (int i = 0; i < k.length; i++) {
            ids.add(new EntityIdentifier(k[i], iperson));
        }
        return (EntityIdentifier[]) ids.toArray(new EntityIdentifier[0]);
    } catch (NamingException nex) {
        throw new GroupsException("LDAPGroupStore: Unable to perform filter " + query, nex);
    }
}
Also used : GroupsException(org.apereo.portal.groups.GroupsException) ArrayList(java.util.ArrayList) NamingEnumeration(javax.naming.NamingEnumeration) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) EntityIdentifier(org.apereo.portal.EntityIdentifier)

Aggregations

DirContext (javax.naming.directory.DirContext)76 NamingException (javax.naming.NamingException)32 InitialDirContext (javax.naming.directory.InitialDirContext)32 SearchResult (javax.naming.directory.SearchResult)26 SearchControls (javax.naming.directory.SearchControls)22 Attributes (javax.naming.directory.Attributes)18 Attribute (javax.naming.directory.Attribute)16 NamingEnumeration (javax.naming.NamingEnumeration)14 Test (org.junit.Test)14 Hashtable (java.util.Hashtable)12 DistinguishedName (org.springframework.ldap.core.DistinguishedName)11 Name (javax.naming.Name)7 DirContextAdapter (org.springframework.ldap.core.DirContextAdapter)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 BasicAttribute (javax.naming.directory.BasicAttribute)6 BasicAttributes (javax.naming.directory.BasicAttributes)6 Authentication (org.springframework.security.core.Authentication)5 Principal (java.security.Principal)3 LdapContext (javax.naming.ldap.LdapContext)3