Browse Source

SEC-2690: Formatting cleanup

pull/117/head
Rob Winch 12 years ago
parent
commit
6b43b261bc
  1. 76
      ldap/src/integration-test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateITests.java
  2. 49
      ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulatorTests.java
  3. 31
      ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java
  4. 2
      ldap/src/main/java/org/springframework/security/ldap/server/ApacheDSContainer.java
  5. 33
      ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapAuthority.java
  6. 57
      ldap/src/main/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulator.java
  7. 8
      ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapAuthorityTests.java

76
ldap/src/integration-test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateITests.java

@ -100,66 +100,66 @@ public class SpringSecurityLdapTemplateITests extends AbstractLdapIntegrationTes
assertTrue(values.contains("submanager")); assertTrue(values.contains("submanager"));
} }
@Test @Test
public void testMultiAttributeRetrievalWithNullAttributeNames() { public void testMultiAttributeRetrievalWithNullAttributeNames() {
Set<Map<String, String[]>> values = Set<Map<String, String[]>> values =
template.searchForMultipleAttributeValues( template.searchForMultipleAttributeValues(
"ou=people", "ou=people",
"(uid={0})", "(uid={0})",
new String[] {"bob"}, new String[]{"bob"},
null); null);
assertEquals(1, values.size()); assertEquals(1, values.size());
Map<String, String[]> record = (Map<String, String[]>)values.toArray()[0]; Map<String, String[]> record = (Map<String, String[]>) values.toArray()[0];
assertAttributeValue(record,"uid","bob"); assertAttributeValue(record, "uid", "bob");
assertAttributeValue(record,"objectclass","top","person","organizationalPerson","inetOrgPerson"); assertAttributeValue(record, "objectclass", "top", "person", "organizationalPerson", "inetOrgPerson");
assertAttributeValue(record,"cn","Bob Hamilton"); assertAttributeValue(record, "cn", "Bob Hamilton");
assertAttributeValue(record,"sn","Hamilton"); assertAttributeValue(record, "sn", "Hamilton");
assertFalse(record.containsKey("userPassword")); assertFalse(record.containsKey("userPassword"));
} }
@Test @Test
public void testMultiAttributeRetrievalWithZeroLengthAttributeNames() { public void testMultiAttributeRetrievalWithZeroLengthAttributeNames() {
Set<Map<String, String[]>> values = Set<Map<String, String[]>> values =
template.searchForMultipleAttributeValues( template.searchForMultipleAttributeValues(
"ou=people", "ou=people",
"(uid={0})", "(uid={0})",
new String[] {"bob"}, new String[]{"bob"},
new String[0]); new String[0]);
assertEquals(1, values.size()); assertEquals(1, values.size());
Map<String, String[]> record = (Map<String, String[]>)values.toArray()[0]; Map<String, String[]> record = (Map<String, String[]>) values.toArray()[0];
assertAttributeValue(record,"uid","bob"); assertAttributeValue(record, "uid", "bob");
assertAttributeValue(record,"objectclass","top","person","organizationalPerson","inetOrgPerson"); assertAttributeValue(record, "objectclass", "top", "person", "organizationalPerson", "inetOrgPerson");
assertAttributeValue(record,"cn","Bob Hamilton"); assertAttributeValue(record, "cn", "Bob Hamilton");
assertAttributeValue(record,"sn","Hamilton"); assertAttributeValue(record, "sn", "Hamilton");
assertFalse(record.containsKey("userPassword")); assertFalse(record.containsKey("userPassword"));
} }
@Test @Test
public void testMultiAttributeRetrievalWithSpecifiedAttributeNames() { public void testMultiAttributeRetrievalWithSpecifiedAttributeNames() {
Set<Map<String, String[]>> values = Set<Map<String, String[]>> values =
template.searchForMultipleAttributeValues( template.searchForMultipleAttributeValues(
"ou=people", "ou=people",
"(uid={0})", "(uid={0})",
new String[] {"bob"}, new String[]{"bob"},
new String[] { new String[]{
"uid", "uid",
"cn", "cn",
"sn" "sn"
}); });
assertEquals(1, values.size()); assertEquals(1, values.size());
Map<String, String[]> record = (Map<String, String[]>)values.toArray()[0]; Map<String, String[]> record = (Map<String, String[]>) values.toArray()[0];
assertAttributeValue(record,"uid","bob"); assertAttributeValue(record, "uid", "bob");
assertAttributeValue(record,"cn","Bob Hamilton"); assertAttributeValue(record, "cn", "Bob Hamilton");
assertAttributeValue(record,"sn","Hamilton"); assertAttributeValue(record, "sn", "Hamilton");
assertFalse(record.containsKey("userPassword")); assertFalse(record.containsKey("userPassword"));
assertFalse(record.containsKey("objectclass")); assertFalse(record.containsKey("objectclass"));
} }
protected void assertAttributeValue(Map<String, String[]> record, String attributeName, String... values) { protected void assertAttributeValue(Map<String, String[]> record, String attributeName, String... values) {
assertTrue(record.containsKey(attributeName)); assertTrue(record.containsKey(attributeName));
assertEquals(values.length,record.get(attributeName).length); assertEquals(values.length, record.get(attributeName).length);
for (int i=0; i<values.length; i++) { for (int i = 0; i < values.length; i++) {
assertEquals(values[i],record.get(attributeName)[i]); assertEquals(values[i], record.get(attributeName)[i]);
} }
} }

49
ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulatorTests.java

@ -25,10 +25,7 @@ import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/** /**
* @author Filip Hanik * @author Filip Hanik
@ -52,18 +49,18 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration
populator.setRolePrefix(""); populator.setRolePrefix("");
populator.setSearchSubtree(true); populator.setSearchSubtree(true);
populator.setConvertToUpperCase(false); populator.setConvertToUpperCase(false);
jDevelopers = new LdapAuthority("j-developers","cn=j-developers,ou=jdeveloper,dc=springframework,dc=org"); jDevelopers = new LdapAuthority("j-developers", "cn=j-developers,ou=jdeveloper,dc=springframework,dc=org");
javaDevelopers = new LdapAuthority("java-developers","cn=java-developers,ou=jdeveloper,dc=springframework,dc=org"); javaDevelopers = new LdapAuthority("java-developers", "cn=java-developers,ou=jdeveloper,dc=springframework,dc=org");
groovyDevelopers = new LdapAuthority("groovy-developers","cn=groovy-developers,ou=jdeveloper,dc=springframework,dc=org"); groovyDevelopers = new LdapAuthority("groovy-developers", "cn=groovy-developers,ou=jdeveloper,dc=springframework,dc=org");
scalaDevelopers = new LdapAuthority("scala-developers","cn=scala-developers,ou=jdeveloper,dc=springframework,dc=org"); scalaDevelopers = new LdapAuthority("scala-developers", "cn=scala-developers,ou=jdeveloper,dc=springframework,dc=org");
closureDevelopers = new LdapAuthority("closure-developers","cn=closure-developers,ou=jdeveloper,dc=springframework,dc=org"); closureDevelopers = new LdapAuthority("closure-developers", "cn=closure-developers,ou=jdeveloper,dc=springframework,dc=org");
circularJavaDevelopers = new LdapAuthority("circular-java-developers","cn=circular-java-developers,ou=jdeveloper,dc=springframework,dc=org"); circularJavaDevelopers = new LdapAuthority("circular-java-developers", "cn=circular-java-developers,ou=jdeveloper,dc=springframework,dc=org");
} }
@Test @Test
public void testScalaDudeJDevelopersAuthorities() { public void testScalaDudeJDevelopersAuthorities() {
DirContextAdapter ctx = new DirContextAdapter("uid=scaladude,ou=people,dc=springframework,dc=org"); DirContextAdapter ctx = new DirContextAdapter("uid=scaladude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,"scaladude"); Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "scaladude");
assertEquals(5, authorities.size()); assertEquals(5, authorities.size());
assertEquals(Arrays.asList(javaDevelopers, scalaDevelopers, circularJavaDevelopers, jDevelopers, groovyDevelopers), authorities); assertEquals(Arrays.asList(javaDevelopers, scalaDevelopers, circularJavaDevelopers, jDevelopers, groovyDevelopers), authorities);
} }
@ -71,7 +68,7 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration
@Test @Test
public void testJavaDudeJDevelopersAuthorities() { public void testJavaDudeJDevelopersAuthorities() {
DirContextAdapter ctx = new DirContextAdapter("uid=javadude,ou=people,dc=springframework,dc=org"); DirContextAdapter ctx = new DirContextAdapter("uid=javadude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,"javadude"); Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "javadude");
assertEquals(3, authorities.size()); assertEquals(3, authorities.size());
assertEquals(Arrays.asList(javaDevelopers, circularJavaDevelopers, jDevelopers), authorities); assertEquals(Arrays.asList(javaDevelopers, circularJavaDevelopers, jDevelopers), authorities);
} }
@ -80,7 +77,7 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration
public void testScalaDudeJDevelopersAuthoritiesWithSearchLimit() { public void testScalaDudeJDevelopersAuthoritiesWithSearchLimit() {
populator.setMaxSearchDepth(1); populator.setMaxSearchDepth(1);
DirContextAdapter ctx = new DirContextAdapter("uid=scaladude,ou=people,dc=springframework,dc=org"); DirContextAdapter ctx = new DirContextAdapter("uid=scaladude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,"scaladude"); Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "scaladude");
assertEquals(1, authorities.size()); assertEquals(1, authorities.size());
assertEquals(Arrays.asList(scalaDevelopers), authorities); assertEquals(Arrays.asList(scalaDevelopers), authorities);
} }
@ -88,9 +85,9 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration
@Test @Test
public void testGroovyDudeJDevelopersAuthorities() { public void testGroovyDudeJDevelopersAuthorities() {
DirContextAdapter ctx = new DirContextAdapter("uid=groovydude,ou=people,dc=springframework,dc=org"); DirContextAdapter ctx = new DirContextAdapter("uid=groovydude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,"groovydude"); Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "groovydude");
assertEquals(4, authorities.size()); assertEquals(4, authorities.size());
assertEquals(Arrays.asList(javaDevelopers,circularJavaDevelopers,jDevelopers,groovyDevelopers), authorities); assertEquals(Arrays.asList(javaDevelopers, circularJavaDevelopers, jDevelopers, groovyDevelopers), authorities);
} }
@Test @Test
@ -98,9 +95,9 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration
populator.setAttributeNames(new HashSet(Arrays.asList("member"))); populator.setAttributeNames(new HashSet(Arrays.asList("member")));
DirContextAdapter ctx = new DirContextAdapter("uid=closuredude,ou=people,dc=springframework,dc=org"); DirContextAdapter ctx = new DirContextAdapter("uid=closuredude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,"closuredude"); Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "closuredude");
assertEquals(5, authorities.size()); assertEquals(5, authorities.size());
assertEquals(Arrays.asList(closureDevelopers,javaDevelopers,circularJavaDevelopers,jDevelopers,groovyDevelopers), authorities); assertEquals(Arrays.asList(closureDevelopers, javaDevelopers, circularJavaDevelopers, jDevelopers, groovyDevelopers), authorities);
LdapAuthority[] ldapAuthorities = authorities.toArray(new LdapAuthority[0]); LdapAuthority[] ldapAuthorities = authorities.toArray(new LdapAuthority[0]);
assertEquals(5, ldapAuthorities.length); assertEquals(5, ldapAuthorities.length);
@ -108,20 +105,20 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration
assertTrue(ldapAuthorities[0].getAttributes().containsKey("member")); assertTrue(ldapAuthorities[0].getAttributes().containsKey("member"));
assertNotNull(ldapAuthorities[0].getAttributes().get("member")); assertNotNull(ldapAuthorities[0].getAttributes().get("member"));
assertEquals(1, ldapAuthorities[0].getAttributes().get("member").length); assertEquals(1, ldapAuthorities[0].getAttributes().get("member").length);
assertEquals("uid=closuredude,ou=people,dc=springframework,dc=org",ldapAuthorities[0].getFirstAttributeValue("member")); assertEquals("uid=closuredude,ou=people,dc=springframework,dc=org", ldapAuthorities[0].getFirstAttributeValue("member"));
//java group //java group
assertTrue(ldapAuthorities[1].getAttributes().containsKey("member")); assertTrue(ldapAuthorities[1].getAttributes().containsKey("member"));
assertNotNull(ldapAuthorities[1].getAttributes().get("member")); assertNotNull(ldapAuthorities[1].getAttributes().get("member"));
assertEquals(3,ldapAuthorities[1].getAttributes().get("member").length); assertEquals(3, ldapAuthorities[1].getAttributes().get("member").length);
assertEquals(groovyDevelopers.getDn(),ldapAuthorities[1].getFirstAttributeValue("member")); assertEquals(groovyDevelopers.getDn(), ldapAuthorities[1].getFirstAttributeValue("member"));
assertEquals( assertEquals(
new String[] { new String[]{
groovyDevelopers.getDn(), groovyDevelopers.getDn(),
scalaDevelopers.getDn(), scalaDevelopers.getDn(),
"uid=javadude,ou=people,dc=springframework,dc=org" "uid=javadude,ou=people,dc=springframework,dc=org"
}, },
ldapAuthorities[1].getAttributes().get("member") ldapAuthorities[1].getAttributes().get("member")
); );
//test non existent attribute //test non existent attribute

31
ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java

@ -152,12 +152,12 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
*/ */
public Set<String> searchForSingleAttributeValues(final String base, final String filter, final Object[] params, public Set<String> searchForSingleAttributeValues(final String base, final String filter, final Object[] params,
final String attributeName) { final String attributeName) {
String[] attributeNames = new String[] {attributeName}; String[] attributeNames = new String[]{attributeName};
Set<Map<String,String[]>> multipleAttributeValues = searchForMultipleAttributeValues(base,filter,params,attributeNames); Set<Map<String, String[]>> multipleAttributeValues = searchForMultipleAttributeValues(base, filter, params, attributeNames);
Set<String> result = new HashSet<String>(); Set<String> result = new HashSet<String>();
for (Map<String,String[]> map : multipleAttributeValues) { for (Map<String, String[]> map : multipleAttributeValues) {
String[] values = map.get(attributeName); String[] values = map.get(attributeName);
if (values!=null && values.length>0) { if (values != null && values.length > 0) {
result.addAll(Arrays.asList(values)); result.addAll(Arrays.asList(values));
} }
} }
@ -183,7 +183,7 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
// Escape the params acording to RFC2254 // Escape the params acording to RFC2254
Object[] encodedParams = new String[params.length]; Object[] encodedParams = new String[params.length];
for (int i=0; i < params.length; i++) { for (int i = 0; i < params.length; i++) {
encodedParams[i] = LdapEncoder.filterEncode(params[i].toString()); encodedParams[i] = LdapEncoder.filterEncode(params[i].toString());
} }
@ -196,13 +196,13 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
public Object mapFromContext(Object ctx) { public Object mapFromContext(Object ctx) {
DirContextAdapter adapter = (DirContextAdapter) ctx; DirContextAdapter adapter = (DirContextAdapter) ctx;
Map<String, String[]> record = new HashMap<String, String[]>(); Map<String, String[]> record = new HashMap<String, String[]>();
if (attributeNames==null||attributeNames.length==0) { if (attributeNames == null || attributeNames.length == 0) {
try { try {
for (NamingEnumeration ae = adapter.getAttributes().getAll(); ae.hasMore(); ) { for (NamingEnumeration ae = adapter.getAttributes().getAll(); ae.hasMore(); ) {
Attribute attr = (Attribute) ae.next(); Attribute attr = (Attribute) ae.next();
extractStringAttributeValues(adapter, record, attr.getID()); extractStringAttributeValues(adapter, record, attr.getID());
} }
}catch (NamingException x) { } catch (NamingException x) {
org.springframework.ldap.support.LdapUtils.convertLdapException(x); org.springframework.ldap.support.LdapUtils.convertLdapException(x);
} }
} else { } else {
@ -210,7 +210,7 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
extractStringAttributeValues(adapter, record, attributeName); extractStringAttributeValues(adapter, record, attributeName);
} }
} }
record.put(DN_KEY, new String[] {getAdapterDN(adapter)}); record.put(DN_KEY, new String[]{getAdapterDN(adapter)});
set.add(record); set.add(record);
return null; return null;
} }
@ -218,7 +218,7 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
SearchControls ctls = new SearchControls(); SearchControls ctls = new SearchControls();
ctls.setSearchScope(searchControls.getSearchScope()); ctls.setSearchScope(searchControls.getSearchScope());
ctls.setReturningAttributes(attributeNames!=null&&attributeNames.length>0?attributeNames:null); ctls.setReturningAttributes(attributeNames != null && attributeNames.length > 0 ? attributeNames : null);
search(base, formattedFilter, ctls, roleMapper); search(base, formattedFilter, ctls, roleMapper);
@ -239,10 +239,11 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
} }
/** /**
* Extracts String values for a specified attribute name and places them in the map representing the ldap record * Extracts String values for a specified attribute name and places them in the map representing the ldap record If
* If a value is not of type String, it will derive it's value from the {@link Object#toString()} * a value is not of type String, it will derive it's value from the {@link Object#toString()}
* @param adapter - the adapter that contains the values *
* @param record - the map holding the attribute names and values * @param adapter - the adapter that contains the values
* @param record - the map holding the attribute names and values
* @param attributeName - the name for which to fetch the values from * @param attributeName - the name for which to fetch the values from
*/ */
protected void extractStringAttributeValues(DirContextAdapter adapter, Map<String, String[]> record, String attributeName) { protected void extractStringAttributeValues(DirContextAdapter adapter, Map<String, String[]> record, String attributeName) {
@ -253,9 +254,9 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
} }
List<String> svalues = new ArrayList<String>(); List<String> svalues = new ArrayList<String>();
for (Object o : values) { for (Object o : values) {
if (o!=null) { if (o != null) {
if (String.class.isAssignableFrom(o.getClass())) { if (String.class.isAssignableFrom(o.getClass())) {
svalues.add((String)o); svalues.add((String) o);
} else { } else {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Attribute:" + attributeName + " contains a non string value of type[" + o.getClass() + "]"); logger.debug("Attribute:" + attributeName + " contains a non string value of type[" + o.getClass() + "]");

2
ldap/src/main/java/org/springframework/security/ldap/server/ApacheDSContainer.java

@ -127,7 +127,7 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
server = new LdapServer(); server = new LdapServer();
server.setDirectoryService(service); server.setDirectoryService(service);
//AbstractLdapIntegrationTests assume IPv4, so we specify the same here // AbstractLdapIntegrationTests assume IPv4, so we specify the same here
server.setTransports(new TcpTransport("127.0.0.1", port)); server.setTransports(new TcpTransport("127.0.0.1", port));
start(); start();
} }

33
ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapAuthority.java

@ -20,9 +20,9 @@ import org.springframework.security.core.GrantedAuthority;
import java.util.Map; import java.util.Map;
/** /**
* An authority that contains at least a DN and a role name for an LDAP entry * An authority that contains at least a DN and a role name for an LDAP entry but can also contain other desired
* but can also contain other desired attributes to be fetched during an LDAP * attributes to be fetched during an LDAP authority search.
* authority search. *
* @author Filip Hanik * @author Filip Hanik
*/ */
public class LdapAuthority implements GrantedAuthority { public class LdapAuthority implements GrantedAuthority {
@ -34,21 +34,23 @@ public class LdapAuthority implements GrantedAuthority {
/** /**
* Constructs an LdapAuthority that has a role and a DN but no other attributes * Constructs an LdapAuthority that has a role and a DN but no other attributes
*
* @param role * @param role
* @param dn * @param dn
*/ */
public LdapAuthority(String role, String dn) { public LdapAuthority(String role, String dn) {
this(role,dn,null); this(role, dn, null);
} }
/** /**
* Constructs an LdapAuthority with the given role, DN and other LDAP attributes * Constructs an LdapAuthority with the given role, DN and other LDAP attributes
*
* @param role * @param role
* @param dn * @param dn
* @param attributes * @param attributes
*/ */
public LdapAuthority(String role, String dn, Map<String,String[]> attributes) { public LdapAuthority(String role, String dn, Map<String, String[]> attributes) {
if (role==null) throw new NullPointerException("role can not be null"); if (role == null) throw new NullPointerException("role can not be null");
this.role = role; this.role = role;
this.dn = dn; this.dn = dn;
this.attributes = attributes; this.attributes = attributes;
@ -56,6 +58,7 @@ public class LdapAuthority implements GrantedAuthority {
/** /**
* Returns the LDAP attributes * Returns the LDAP attributes
*
* @return the LDAP attributes, map can be null * @return the LDAP attributes, map can be null
*/ */
public Map<String, String[]> getAttributes() { public Map<String, String[]> getAttributes() {
@ -64,6 +67,7 @@ public class LdapAuthority implements GrantedAuthority {
/** /**
* Returns the DN for this LDAP authority * Returns the DN for this LDAP authority
*
* @return * @return
*/ */
public String getDn() { public String getDn() {
@ -72,15 +76,16 @@ public class LdapAuthority implements GrantedAuthority {
/** /**
* Returns the values for a specific attribute * Returns the values for a specific attribute
*
* @param name the attribute name * @param name the attribute name
* @return a String array, never null but may be zero length * @return a String array, never null but may be zero length
*/ */
public String[] getAttributeValues(String name) { public String[] getAttributeValues(String name) {
String[] result = null; String[] result = null;
if (attributes!=null) { if (attributes != null) {
result = attributes.get(name); result = attributes.get(name);
} }
if (result==null) { if (result == null) {
result = new String[0]; result = new String[0];
} }
return result; return result;
@ -88,12 +93,13 @@ public class LdapAuthority implements GrantedAuthority {
/** /**
* Returns the first attribute value for a specified attribute * Returns the first attribute value for a specified attribute
*
* @param name * @param name
* @return the first attribute value for a specified attribute, may be null * @return the first attribute value for a specified attribute, may be null
*/ */
public String getFirstAttributeValue(String name) { public String getFirstAttributeValue(String name) {
String[] result = getAttributeValues(name); String[] result = getAttributeValues(name);
if (result.length>0) { if (result.length > 0) {
return result[0]; return result[0];
} else { } else {
return null; return null;
@ -109,8 +115,7 @@ public class LdapAuthority implements GrantedAuthority {
} }
/** /**
* Compares the LdapAuthority based on {@link #getAuthority()} and {@link #getDn()} values * Compares the LdapAuthority based on {@link #getAuthority()} and {@link #getDn()} values {@inheritDoc}
* {@inheritDoc}
*/ */
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
@ -135,8 +140,8 @@ public class LdapAuthority implements GrantedAuthority {
@Override @Override
public String toString() { public String toString() {
return "LdapAuthority{" + return "LdapAuthority{" +
"dn='" + dn + '\'' + "dn='" + dn + '\'' +
", role='" + role + '\'' + ", role='" + role + '\'' +
'}'; '}';
} }
} }

57
ldap/src/main/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulator.java

@ -28,8 +28,7 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
/** /**
* A LDAP authority populator that can recursively search static nested groups. * A LDAP authority populator that can recursively search static nested groups. <p>An example of nested groups can be
* <p>An example of nested groups can be
* <pre> * <pre>
* #Nested groups data * #Nested groups data
* *
@ -128,9 +127,9 @@ public class NestedLdapAuthoritiesPopulator extends DefaultLdapAuthoritiesPopula
* Maximum search depth - represents the number of recursive searches performed * Maximum search depth - represents the number of recursive searches performed
*/ */
private int maxSearchDepth = 10; private int maxSearchDepth = 10;
/** /**
* Constructor for group search scenarios. <tt>userRoleAttributes</tt> may still be * Constructor for group search scenarios. <tt>userRoleAttributes</tt> may still be set as a property.
* set as a property.
* *
* @param contextSource supplies the contexts used to search for user roles. * @param contextSource supplies the contexts used to search for user roles.
* @param groupSearchBase if this is an empty string the search will be performed from the root DN of the * @param groupSearchBase if this is an empty string the search will be performed from the root DN of the
@ -157,50 +156,51 @@ public class NestedLdapAuthoritiesPopulator extends DefaultLdapAuthoritiesPopula
/** /**
* Performs the nested group search * Performs the nested group search
* @param userDn - the userDN to search for, will become the group DN for subsequent searches *
* @param username - the username of the user * @param userDn - the userDN to search for, will become the group DN for subsequent searches
* @param username - the username of the user
* @param authorities - the authorities set that will be populated, must not be null * @param authorities - the authorities set that will be populated, must not be null
* @param depth - the depth remaining, when 0 recursion will end * @param depth - the depth remaining, when 0 recursion will end
*/ */
protected void performNestedSearch(String userDn, String username, Set<GrantedAuthority> authorities, int depth) { protected void performNestedSearch(String userDn, String username, Set<GrantedAuthority> authorities, int depth) {
if (depth==0) { if (depth == 0) {
//back out of recursion //back out of recursion
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Search aborted, max depth reached," + logger.debug("Search aborted, max depth reached," +
" for roles for user '" + username + "', DN = " + "'" + userDn + "', with filter " " for roles for user '" + username + "', DN = " + "'" + userDn + "', with filter "
+ getGroupSearchFilter() + " in search base '" + getGroupSearchBase() + "'"); + getGroupSearchFilter() + " in search base '" + getGroupSearchBase() + "'");
} }
return; return;
} }
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Searching for roles for user '" + username + "', DN = " + "'" + userDn + "', with filter " logger.debug("Searching for roles for user '" + username + "', DN = " + "'" + userDn + "', with filter "
+ getGroupSearchFilter() + " in search base '" + getGroupSearchBase() + "'"); + getGroupSearchFilter() + " in search base '" + getGroupSearchBase() + "'");
} }
if (getAttributeNames()==null) { if (getAttributeNames() == null) {
setAttributeNames(new HashSet<String>()); setAttributeNames(new HashSet<String>());
} }
if (StringUtils.hasText(getGroupRoleAttribute()) && !getAttributeNames().contains(getGroupRoleAttribute())) { if (StringUtils.hasText(getGroupRoleAttribute()) && !getAttributeNames().contains(getGroupRoleAttribute())) {
getAttributeNames().add(getGroupRoleAttribute()); getAttributeNames().add(getGroupRoleAttribute());
} }
Set<Map<String,String[]>> userRoles = getLdapTemplate().searchForMultipleAttributeValues( Set<Map<String, String[]>> userRoles = getLdapTemplate().searchForMultipleAttributeValues(
getGroupSearchBase(), getGroupSearchBase(),
getGroupSearchFilter(), getGroupSearchFilter(),
new String[]{userDn, username}, new String[]{userDn, username},
getAttributeNames().toArray(new String[getAttributeNames().size()])); getAttributeNames().toArray(new String[getAttributeNames().size()]));
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Roles from search: " + userRoles); logger.debug("Roles from search: " + userRoles);
} }
for (Map<String,String[]> record : userRoles) { for (Map<String, String[]> record : userRoles) {
boolean circular = false; boolean circular = false;
String dn = record.get(SpringSecurityLdapTemplate.DN_KEY)[0]; String dn = record.get(SpringSecurityLdapTemplate.DN_KEY)[0];
String[] roleValues = record.get(getGroupRoleAttribute()); String[] roleValues = record.get(getGroupRoleAttribute());
Set<String> roles = new HashSet<String>(); Set<String> roles = new HashSet<String>();
roles.addAll(Arrays.asList(roleValues!=null?roleValues:new String[0])); roles.addAll(Arrays.asList(roleValues != null ? roleValues : new String[0]));
for (String role : roles) { for (String role : roles) {
if (isConvertToUpperCase()) { if (isConvertToUpperCase()) {
role = role.toUpperCase(); role = role.toUpperCase();
@ -208,9 +208,9 @@ public class NestedLdapAuthoritiesPopulator extends DefaultLdapAuthoritiesPopula
role = getRolePrefix() + role; role = getRolePrefix() + role;
//if the group already exist, we will not search for it's parents again. //if the group already exist, we will not search for it's parents again.
//this prevents a forever loop for a misconfigured ldap directory //this prevents a forever loop for a misconfigured ldap directory
circular = circular | (!authorities.add(new LdapAuthority(role,dn,record))); circular = circular | (!authorities.add(new LdapAuthority(role, dn, record)));
} }
String roleName = roles.size()>0 ? roles.iterator().next() : dn; String roleName = roles.size() > 0 ? roles.iterator().next() : dn;
if (!circular) { if (!circular) {
performNestedSearch(dn, roleName, authorities, (depth - 1)); performNestedSearch(dn, roleName, authorities, (depth - 1));
} }
@ -219,8 +219,9 @@ public class NestedLdapAuthoritiesPopulator extends DefaultLdapAuthoritiesPopula
} }
/** /**
* Returns the attribute names that this populator has been configured to retrieve * Returns the attribute names that this populator has been configured to retrieve Value can be null, represents
* Value can be null, represents fetch all attributes * fetch all attributes
*
* @return the attribute names or null for all * @return the attribute names or null for all
*/ */
public Set<String> getAttributeNames() { public Set<String> getAttributeNames() {
@ -229,6 +230,7 @@ public class NestedLdapAuthoritiesPopulator extends DefaultLdapAuthoritiesPopula
/** /**
* Sets the attribute names to retrieve for each ldap groups. Null means retrieve all * Sets the attribute names to retrieve for each ldap groups. Null means retrieve all
*
* @param attributeNames - the names of the LDAP attributes to retrieve * @param attributeNames - the names of the LDAP attributes to retrieve
*/ */
public void setAttributeNames(Set<String> attributeNames) { public void setAttributeNames(Set<String> attributeNames) {
@ -236,8 +238,8 @@ public class NestedLdapAuthoritiesPopulator extends DefaultLdapAuthoritiesPopula
} }
/** /**
* How far should a nested search go. Depth is calculated in the number of levels we search up for * How far should a nested search go. Depth is calculated in the number of levels we search up for parent groups.
* parent groups. *
* @return the max search depth, default is 10 * @return the max search depth, default is 10
*/ */
public int getMaxSearchDepth() { public int getMaxSearchDepth() {
@ -245,8 +247,8 @@ public class NestedLdapAuthoritiesPopulator extends DefaultLdapAuthoritiesPopula
} }
/** /**
* How far should a nested search go. Depth is calculated in the number of levels we search up for * How far should a nested search go. Depth is calculated in the number of levels we search up for parent groups.
* parent groups. *
* @param maxSearchDepth the max search depth * @param maxSearchDepth the max search depth
*/ */
public void setMaxSearchDepth(int maxSearchDepth) { public void setMaxSearchDepth(int maxSearchDepth) {
@ -254,5 +256,4 @@ public class NestedLdapAuthoritiesPopulator extends DefaultLdapAuthoritiesPopula
} }
} }

8
ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapAuthorityTests.java

@ -20,9 +20,9 @@ public class LdapAuthorityTests {
@Before @Before
public void setUp() { public void setUp() {
Map<String,String[]> attributes = new HashMap<String,String[]>(); Map<String, String[]> attributes = new HashMap<String, String[]>();
attributes.put(SpringSecurityLdapTemplate.DN_KEY,new String[] {DN}); attributes.put(SpringSecurityLdapTemplate.DN_KEY, new String[]{DN});
attributes.put("mail",new String[] {"filip@ldap.test.org", "filip@ldap.test2.org"}); attributes.put("mail", new String[]{"filip@ldap.test.org", "filip@ldap.test2.org"});
authority = new LdapAuthority("testRole", DN, attributes); authority = new LdapAuthority("testRole", DN, attributes);
} }
@ -47,6 +47,6 @@ public class LdapAuthorityTests {
@Test @Test
public void testGetAuthority() throws Exception { public void testGetAuthority() throws Exception {
assertNotNull(authority.getAuthority()); assertNotNull(authority.getAuthority());
assertEquals("testRole",authority.getAuthority()); assertEquals("testRole", authority.getAuthority());
} }
} }
Loading…
Cancel
Save