Reformat code using spring-javaformat

Run `./gradlew format` to reformat all java files.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-08-10 16:39:17 -05:00
committed by Rob Winch
parent 81d9c6cac5
commit b7fc18262d
2487 changed files with 41506 additions and 46548 deletions

View File

@@ -32,16 +32,15 @@ public class ApacheDsContainerConfig {
@Bean
ApacheDSContainer ldapContainer() throws Exception {
this.container = new ApacheDSContainer("dc=springframework,dc=org",
"classpath:test-server.ldif");
this.container = new ApacheDSContainer("dc=springframework,dc=org", "classpath:test-server.ldif");
this.container.setPort(0);
return this.container;
}
@Bean
ContextSource contextSource(ApacheDSContainer ldapContainer) throws Exception {
return new DefaultSpringSecurityContextSource("ldap://127.0.0.1:"
+ ldapContainer.getLocalPort() + "/dc=springframework,dc=org");
return new DefaultSpringSecurityContextSource(
"ldap://127.0.0.1:" + ldapContainer.getLocalPort() + "/dc=springframework,dc=org");
}
@PreDestroy

View File

@@ -53,8 +53,7 @@ public class DefaultSpringSecurityContextSourceTests {
@Test
public void supportsSpacesInUrl() {
new DefaultSpringSecurityContextSource(
"ldap://myhost:10389/dc=spring%20framework,dc=org");
new DefaultSpringSecurityContextSource("ldap://myhost:10389/dc=spring%20framework,dc=org");
}
@Test
@@ -64,8 +63,8 @@ public class DefaultSpringSecurityContextSourceTests {
ctxSrc.setUserDn("manager");
ctxSrc.setPassword("password");
ctxSrc.afterPropertiesSet();
assertThat(ctxSrc.getAuthenticatedEnvForTest("manager", "password")).containsKey(
AbstractContextSource.SUN_LDAP_POOLING_FLAG);
assertThat(ctxSrc.getAuthenticatedEnvForTest("manager", "password"))
.containsKey(AbstractContextSource.SUN_LDAP_POOLING_FLAG);
}
@Test
@@ -75,18 +74,16 @@ public class DefaultSpringSecurityContextSourceTests {
ctxSrc.setUserDn("manager");
ctxSrc.setPassword("password");
ctxSrc.afterPropertiesSet();
assertThat(ctxSrc.getAuthenticatedEnvForTest("user", "password")).doesNotContainKey(
AbstractContextSource.SUN_LDAP_POOLING_FLAG);
assertThat(ctxSrc.getAuthenticatedEnvForTest("user", "password"))
.doesNotContainKey(AbstractContextSource.SUN_LDAP_POOLING_FLAG);
}
// SEC-1145. Confirms that there is no issue here with pooling.
@Test(expected = AuthenticationException.class)
public void cantBindWithWrongPasswordImmediatelyAfterSuccessfulBind()
throws Exception {
public void cantBindWithWrongPasswordImmediatelyAfterSuccessfulBind() throws Exception {
DirContext ctx = null;
try {
ctx = this.contextSource.getContext(
"uid=Bob,ou=people,dc=springframework,dc=org", "bobspassword");
ctx = this.contextSource.getContext("uid=Bob,ou=people,dc=springframework,dc=org", "bobspassword");
}
catch (Exception e) {
}
@@ -95,27 +92,23 @@ public class DefaultSpringSecurityContextSourceTests {
ctx.close();
// com.sun.jndi.ldap.LdapPoolManager.showStats(System.out);
// Now get it gain, with wrong password. Should fail.
ctx = this.contextSource.getContext(
"uid=Bob,ou=people,dc=springframework,dc=org", "wrongpassword");
ctx = this.contextSource.getContext("uid=Bob,ou=people,dc=springframework,dc=org", "wrongpassword");
ctx.close();
}
@Test
public void serverUrlWithSpacesIsSupported() {
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(
this.contextSource.getUrls()[0]
+ "ou=space%20cadets,dc=springframework,dc=org");
this.contextSource.getUrls()[0] + "ou=space%20cadets,dc=springframework,dc=org");
contextSource.afterPropertiesSet();
contextSource.getContext(
"uid=space cadet,ou=space cadets,dc=springframework,dc=org",
"spacecadetspassword");
contextSource.getContext("uid=space cadet,ou=space cadets,dc=springframework,dc=org", "spacecadetspassword");
}
@Test(expected = IllegalArgumentException.class)
public void instantiationFailsWithEmptyServerList() {
List<String> serverUrls = new ArrayList<>();
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(
serverUrls, "dc=springframework,dc=org");
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(serverUrls,
"dc=springframework,dc=org");
ctxSrc.afterPropertiesSet();
}
@@ -125,8 +118,8 @@ public class DefaultSpringSecurityContextSourceTests {
serverUrls.add("ldap://foo:789");
serverUrls.add("ldap://bar:389");
serverUrls.add("ldaps://blah:636");
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(
serverUrls, "dc=springframework,dc=org");
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(serverUrls,
"dc=springframework,dc=org");
assertThat(ctxSrc.isAnonymousReadOnly()).isFalse();
assertThat(ctxSrc.isPooled()).isTrue();
@@ -140,8 +133,7 @@ public class DefaultSpringSecurityContextSourceTests {
serverUrls.add("ldap://foo:789");
serverUrls.add("ldap://bar:389");
serverUrls.add("ldaps://blah:636");
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(
serverUrls, baseDn);
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(serverUrls, baseDn);
assertThat(ctxSrc.isAnonymousReadOnly()).isFalse();
assertThat(ctxSrc.isPooled()).isTrue();
@@ -154,12 +146,12 @@ public class DefaultSpringSecurityContextSourceTests {
serverUrls.add("ldaps://blah:636/");
// this url should be rejected because the root DN goes into a separate parameter
serverUrls.add("ldap://bar:389/dc=foobar,dc=org");
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(
serverUrls, "dc=springframework,dc=org");
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(serverUrls,
"dc=springframework,dc=org");
}
static class EnvExposingDefaultSpringSecurityContextSource extends
DefaultSpringSecurityContextSource {
static class EnvExposingDefaultSpringSecurityContextSource extends DefaultSpringSecurityContextSource {
EnvExposingDefaultSpringSecurityContextSource(String providerUrl) {
super(providerUrl);
}
@@ -168,5 +160,7 @@ public class DefaultSpringSecurityContextSourceTests {
Hashtable getAuthenticatedEnvForTest(String userDn, String password) {
return getAuthenticatedEnv(userDn, password);
}
}
}

View File

@@ -45,11 +45,13 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ApacheDsContainerConfig.class)
public class SpringSecurityLdapTemplateITests {
// ~ Instance fields
// ================================================================================================
@Autowired
private DefaultSpringSecurityContextSource contextSource;
private SpringSecurityLdapTemplate template;
// ~ Methods
@@ -67,14 +69,12 @@ public class SpringSecurityLdapTemplateITests {
@Test
public void compareOfCorrectByteValueSucceeds() {
assertThat(template.compare("uid=bob,ou=people", "userPassword",
Utf8.encode("bobspassword"))).isTrue();
assertThat(template.compare("uid=bob,ou=people", "userPassword", Utf8.encode("bobspassword"))).isTrue();
}
@Test
public void compareOfWrongByteValueFails() {
assertThat(template.compare("uid=bob,ou=people", "userPassword",
Utf8.encode("wrongvalue"))).isFalse();
assertThat(template.compare("uid=bob,ou=people", "userPassword", Utf8.encode("wrongvalue"))).isFalse();
}
@Test
@@ -108,8 +108,8 @@ public class SpringSecurityLdapTemplateITests {
public void roleSearchReturnsCorrectNumberOfRoles() {
String param = "uid=ben,ou=people,dc=springframework,dc=org";
Set<String> values = template.searchForSingleAttributeValues("ou=groups",
"(member={0})", new String[] { param }, "ou");
Set<String> values = template.searchForSingleAttributeValues("ou=groups", "(member={0})",
new String[] { param }, "ou");
assertThat(values).as("Expected 3 results from search").hasSize(3);
assertThat(values.contains("developer")).isTrue();
@@ -119,14 +119,12 @@ public class SpringSecurityLdapTemplateITests {
@Test
public void testMultiAttributeRetrievalWithNullAttributeNames() {
Set<Map<String, List<String>>> values = template
.searchForMultipleAttributeValues("ou=people", "(uid={0})",
new String[] { "bob" }, null);
Set<Map<String, List<String>>> values = template.searchForMultipleAttributeValues("ou=people", "(uid={0})",
new String[] { "bob" }, null);
assertThat(values).hasSize(1);
Map<String, List<String>> record = values.iterator().next();
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, "sn", "Hamilton");
assertThat(record.containsKey("userPassword")).isFalse();
@@ -134,14 +132,12 @@ public class SpringSecurityLdapTemplateITests {
@Test
public void testMultiAttributeRetrievalWithZeroLengthAttributeNames() {
Set<Map<String, List<String>>> values = template
.searchForMultipleAttributeValues("ou=people", "(uid={0})",
new String[] { "bob" }, new String[0]);
Set<Map<String, List<String>>> values = template.searchForMultipleAttributeValues("ou=people", "(uid={0})",
new String[] { "bob" }, new String[0]);
assertThat(values).hasSize(1);
Map<String, List<String>> record = values.iterator().next();
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, "sn", "Hamilton");
assertThat(record.containsKey("userPassword")).isFalse();
@@ -149,9 +145,8 @@ public class SpringSecurityLdapTemplateITests {
@Test
public void testMultiAttributeRetrievalWithSpecifiedAttributeNames() {
Set<Map<String, List<String>>> values = template
.searchForMultipleAttributeValues("ou=people", "(uid={0})",
new String[] { "bob" }, new String[] { "uid", "cn", "sn" });
Set<Map<String, List<String>>> values = template.searchForMultipleAttributeValues("ou=people", "(uid={0})",
new String[] { "bob" }, new String[] { "uid", "cn", "sn" });
assertThat(values).hasSize(1);
Map<String, List<String>> record = values.iterator().next();
assertAttributeValue(record, "uid", "bob");
@@ -161,8 +156,7 @@ public class SpringSecurityLdapTemplateITests {
assertThat(record.containsKey("objectclass")).isFalse();
}
protected void assertAttributeValue(Map<String, List<String>> record,
String attributeName, String... values) {
protected void assertAttributeValue(Map<String, List<String>> record, String attributeName, String... values) {
assertThat(record.containsKey(attributeName)).isTrue();
assertThat(record.get(attributeName)).hasSize(values.length);
for (int i = 0; i < values.length; i++) {
@@ -174,8 +168,8 @@ public class SpringSecurityLdapTemplateITests {
public void testRoleSearchForMissingAttributeFailsGracefully() {
String param = "uid=ben,ou=people,dc=springframework,dc=org";
Set<String> values = template.searchForSingleAttributeValues("ou=groups",
"(member={0})", new String[] { param }, "mail");
Set<String> values = template.searchForSingleAttributeValues("ou=groups", "(member={0})",
new String[] { param }, "mail");
assertThat(values).isEmpty();
}
@@ -184,8 +178,8 @@ public class SpringSecurityLdapTemplateITests {
public void roleSearchWithEscapedCharacterSucceeds() {
String param = "cn=mouse\\, jerry,ou=people,dc=springframework,dc=org";
Set<String> values = template.searchForSingleAttributeValues("ou=groups",
"(member={0})", new String[] { param }, "cn");
Set<String> values = template.searchForSingleAttributeValues("ou=groups", "(member={0})",
new String[] { param }, "cn");
assertThat(values).hasSize(1);
}
@@ -205,9 +199,8 @@ public class SpringSecurityLdapTemplateITests {
controls.setReturningAttributes(null);
String param = "cn=mouse\\, jerry,ou=people,dc=springframework,dc=org";
javax.naming.NamingEnumeration<SearchResult> results = ctx.search(
"ou=groups,dc=springframework,dc=org", "(member={0})",
new String[] { param }, controls);
javax.naming.NamingEnumeration<SearchResult> results = ctx.search("ou=groups,dc=springframework,dc=org",
"(member={0})", new String[] { param }, controls);
assertThat(results.hasMore()).as("Expected a result").isTrue();
}

View File

@@ -35,7 +35,6 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
/**
* Tests for {@link BindAuthenticator}.
*
@@ -45,12 +44,15 @@ import static org.assertj.core.api.Assertions.fail;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ApacheDsContainerConfig.class)
public class BindAuthenticatorTests {
// ~ Instance fields
// ================================================================================================
@Autowired
private DefaultSpringSecurityContextSource contextSource;
private BindAuthenticator authenticator;
private Authentication bob;
// ~ Methods
@@ -66,19 +68,16 @@ public class BindAuthenticatorTests {
@Test(expected = BadCredentialsException.class)
public void emptyPasswordIsRejected() {
this.authenticator
.authenticate(new UsernamePasswordAuthenticationToken("jen", ""));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("jen", ""));
}
@Test
public void testAuthenticationWithCorrectPasswordSucceeds() {
this.authenticator.setUserDnPatterns(
new String[] { "uid={0},ou=people", "cn={0},ou=people" });
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people", "cn={0},ou=people" });
DirContextOperations user = this.authenticator.authenticate(this.bob);
assertThat(user.getStringAttribute("uid")).isEqualTo("bob");
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken(
"mouse, jerry", "jerryspassword"));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("mouse, jerry", "jerryspassword"));
}
@Test
@@ -86,8 +85,7 @@ public class BindAuthenticatorTests {
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
try {
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken(
"nonexistentsuser", "password"));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("nonexistentsuser", "password"));
fail("Shouldn't be able to bind with invalid username");
}
catch (BadCredentialsException expected) {
@@ -98,28 +96,21 @@ public class BindAuthenticatorTests {
public void testAuthenticationWithUserSearch() throws Exception {
// DirContextAdapter ctx = new DirContextAdapter(new
// DistinguishedName("uid=bob,ou=people"));
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("ou=people",
"(uid={0})", this.contextSource));
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("ou=people", "(uid={0})", this.contextSource));
this.authenticator.afterPropertiesSet();
DirContextOperations result = this.authenticator.authenticate(this.bob);
//ensure we are getting the same attributes back
// ensure we are getting the same attributes back
assertThat(result.getStringAttribute("cn")).isEqualTo("Bob Hamilton");
// SEC-1444
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("ou=people",
"(cn={0})", this.contextSource));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken(
"mouse, jerry", "jerryspassword"));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken(
"slash/guy", "slashguyspassword"));
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("ou=people", "(cn={0})", this.contextSource));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("mouse, jerry", "jerryspassword"));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("slash/guy", "slashguyspassword"));
// SEC-1661
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch(
"ou=\\\"quoted people\\\"", "(cn={0})", this.contextSource));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken(
"quote\"guy", "quoteguyspassword"));
this.authenticator.setUserSearch(
new FilterBasedLdapUserSearch("", "(cn={0})", this.contextSource));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken(
"quote\"guy", "quoteguyspassword"));
new FilterBasedLdapUserSearch("ou=\\\"quoted people\\\"", "(cn={0})", this.contextSource));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("quote\"guy", "quoteguyspassword"));
this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("", "(cn={0})", this.contextSource));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("quote\"guy", "quoteguyspassword"));
}
/*
@@ -148,8 +139,7 @@ public class BindAuthenticatorTests {
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
try {
this.authenticator.authenticate(
new UsernamePasswordAuthenticationToken("bob", "wrongpassword"));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpassword"));
fail("Shouldn't be able to bind with wrong password");
}
catch (BadCredentialsException expected) {
@@ -159,7 +149,7 @@ public class BindAuthenticatorTests {
@Test
public void testUserDnPatternReturnsCorrectDn() {
this.authenticator.setUserDnPatterns(new String[] { "cn={0},ou=people" });
assertThat(this.authenticator.getUserDns("Joe").get(0))
.isEqualTo("cn=Joe,ou=people");
assertThat(this.authenticator.getUserDns("Joe").get(0)).isEqualTo("cn=Joe,ou=people");
}
}

View File

@@ -46,13 +46,17 @@ import static org.assertj.core.api.Assertions.*;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ApacheDsContainerConfig.class)
public class PasswordComparisonAuthenticatorTests {
// ~ Instance fields
// ================================================================================================
@Autowired
private DefaultSpringSecurityContextSource contextSource;
private PasswordComparisonAuthenticator authenticator;
private Authentication bob;
private Authentication ben;
// ~ Methods
@@ -82,8 +86,7 @@ public class PasswordComparisonAuthenticatorTests {
authenticator.afterPropertiesSet();
try {
authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe",
"pass"));
authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass"));
fail("Expected exception on failed user search");
}
catch (UsernameNotFoundException expected) {
@@ -94,14 +97,12 @@ public class PasswordComparisonAuthenticatorTests {
public void testLdapPasswordCompareFailsWithWrongPassword() {
// Don't retrieve the password
authenticator.setUserAttributes(new String[] { "uid", "cn", "sn" });
authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob",
"wrongpass"));
authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpass"));
}
@Test
public void testMultipleDnPatternsWorkOk() {
authenticator.setUserDnPatterns(new String[] { "uid={0},ou=nonexistent",
"uid={0},ou=people" });
authenticator.setUserDnPatterns(new String[] { "uid={0},ou=nonexistent", "uid={0},ou=people" });
authenticator.authenticate(bob);
}
@@ -110,8 +111,7 @@ public class PasswordComparisonAuthenticatorTests {
authenticator.setUserAttributes(new String[] { "uid", "userPassword" });
DirContextAdapter user = (DirContextAdapter) authenticator.authenticate(bob);
assertThat(user
.getAttributes().size()).withFailMessage("Should have retrieved 2 attribute (uid)").isEqualTo(2);
assertThat(user.getAttributes().size()).withFailMessage("Should have retrieved 2 attribute (uid)").isEqualTo(2);
}
@Test
@@ -145,8 +145,7 @@ public class PasswordComparisonAuthenticatorTests {
public void testLdapCompareWithDifferentPasswordAttributeSucceeds() {
authenticator.setUserAttributes(new String[] { "uid" });
authenticator.setPasswordAttributeName("cn");
authenticator.authenticate(new UsernamePasswordAuthenticationToken("ben",
"Ben Alex"));
authenticator.authenticate(new UsernamePasswordAuthenticationToken("ben", "Ben Alex"));
}
@Test
@@ -155,12 +154,11 @@ public class PasswordComparisonAuthenticatorTests {
authenticator.setPasswordEncoder(NoOpPasswordEncoder.getInstance());
assertThat(authenticator.getUserDns("Bob")).withFailMessage("User DN matches shouldn't be available").isEmpty();
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName(
"uid=Bob,ou=people"));
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("uid=Bob,ou=people"));
ctx.setAttributeValue("userPassword", "bobspassword");
authenticator.setUserSearch(new MockUserSearch(ctx));
authenticator.authenticate(new UsernamePasswordAuthenticationToken(
"shouldntbeused", "bobspassword"));
authenticator.authenticate(new UsernamePasswordAuthenticationToken("shouldntbeused", "bobspassword"));
}
}

View File

@@ -47,8 +47,7 @@ public class FilterBasedLdapUserSearchTests {
@Test
public void basicSearchSucceeds() throws Exception {
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people",
"(uid={0})", this.contextSource);
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people", "(uid={0})", this.contextSource);
locator.setSearchSubtree(false);
locator.setSearchTimeLimit(0);
locator.setDerefLinkFlag(false);
@@ -61,8 +60,7 @@ public class FilterBasedLdapUserSearchTests {
@Test
public void searchForNameWithCommaSucceeds() throws Exception {
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people",
"(uid={0})", this.contextSource);
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people", "(uid={0})", this.contextSource);
locator.setSearchSubtree(false);
DirContextOperations jerry = locator.searchForUser("jerry");
@@ -74,8 +72,7 @@ public class FilterBasedLdapUserSearchTests {
// Try some funny business with filters.
@Test
public void extraFilterPartToExcludeBob() {
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch(
"ou=people",
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people",
"(&(cn=*)(!(|(uid={0})(uid=rod)(uid=jerry)(uid=slashguy)(uid=javadude)(uid=groovydude)(uid=closuredude)(uid=scaladude))))",
this.contextSource);
@@ -86,23 +83,20 @@ public class FilterBasedLdapUserSearchTests {
@Test(expected = IncorrectResultSizeDataAccessException.class)
public void searchFailsOnMultipleMatches() {
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people",
"(cn=*)", this.contextSource);
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people", "(cn=*)", this.contextSource);
locator.searchForUser("Ignored");
}
@Test(expected = UsernameNotFoundException.class)
public void searchForInvalidUserFails() {
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people",
"(uid={0})", this.contextSource);
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people", "(uid={0})", this.contextSource);
locator.searchForUser("Joe");
}
@Test
public void subTreeSearchSucceeds() throws Exception {
// Don't set the searchBase, so search from the root.
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("", "(cn={0})",
this.contextSource);
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("", "(cn={0})", this.contextSource);
locator.setSearchSubtree(true);
DirContextOperations ben = locator.searchForUser("Ben Alex");
@@ -113,8 +107,8 @@ public class FilterBasedLdapUserSearchTests {
@Test
public void searchWithDifferentSearchBaseIsSuccessful() {
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch(
"ou=otherpeople", "(cn={0})", this.contextSource);
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=otherpeople", "(cn={0})",
this.contextSource);
DirContextOperations joe = locator.searchForUser("Joe Smeth");
assertThat(joe.getStringAttribute("cn")).isEqualTo("Joe Smeth");
}

View File

@@ -50,10 +50,8 @@ public class ApacheDSContainerTests {
// SEC-2162
@Test
public void failsToStartThrowsException() throws Exception {
ApacheDSContainer server1 = new ApacheDSContainer("dc=springframework,dc=org",
"classpath:test-server.ldif");
ApacheDSContainer server2 = new ApacheDSContainer("dc=springframework,dc=org",
"classpath:missing.ldif");
ApacheDSContainer server1 = new ApacheDSContainer("dc=springframework,dc=org", "classpath:test-server.ldif");
ApacheDSContainer server2 = new ApacheDSContainer("dc=springframework,dc=org", "classpath:missing.ldif");
List<Integer> ports = getDefaultPorts(1);
server1.setPort(ports.get(0));
server2.setPort(ports.get(0));
@@ -83,10 +81,8 @@ public class ApacheDSContainerTests {
// SEC-2161
@Test
public void multipleInstancesSimultanciously() throws Exception {
ApacheDSContainer server1 = new ApacheDSContainer("dc=springframework,dc=org",
"classpath:test-server.ldif");
ApacheDSContainer server2 = new ApacheDSContainer("dc=springframework,dc=org",
"classpath:test-server.ldif");
ApacheDSContainer server1 = new ApacheDSContainer("dc=springframework,dc=org", "classpath:test-server.ldif");
ApacheDSContainer server2 = new ApacheDSContainer("dc=springframework,dc=org", "classpath:test-server.ldif");
List<Integer> ports = getDefaultPorts(2);
server1.setPort(ports.get(0));
server2.setPort(ports.get(1));
@@ -110,8 +106,7 @@ public class ApacheDSContainerTests {
@Test
public void startWithLdapOverSslWithoutCertificate() throws Exception {
ApacheDSContainer server = new ApacheDSContainer("dc=springframework,dc=org",
"classpath:test-server.ldif");
ApacheDSContainer server = new ApacheDSContainer("dc=springframework,dc=org", "classpath:test-server.ldif");
List<Integer> ports = getDefaultPorts(1);
server.setPort(ports.get(0));
server.setLdapOverSslEnabled(true);
@@ -120,21 +115,21 @@ public class ApacheDSContainerTests {
server.afterPropertiesSet();
fail("Expected an IllegalArgumentException to be thrown.");
}
catch (IllegalArgumentException e){
catch (IllegalArgumentException e) {
assertThat(e).hasMessage("When LdapOverSsl is enabled, the keyStoreFile property must be set.");
}
}
@Test
public void startWithLdapOverSslWithWrongPassword() throws Exception {
final ClassPathResource keyStoreResource = new ClassPathResource("/org/springframework/security/ldap/server/spring.keystore");
final ClassPathResource keyStoreResource = new ClassPathResource(
"/org/springframework/security/ldap/server/spring.keystore");
final File temporaryKeyStoreFile = new File(temporaryFolder.getRoot(), "spring.keystore");
FileCopyUtils.copy(keyStoreResource.getInputStream(), new FileOutputStream(temporaryKeyStoreFile));
assertThat(temporaryKeyStoreFile).isFile();
ApacheDSContainer server = new ApacheDSContainer("dc=springframework,dc=org",
"classpath:test-server.ldif");
ApacheDSContainer server = new ApacheDSContainer("dc=springframework,dc=org", "classpath:test-server.ldif");
List<Integer> ports = getDefaultPorts(1);
server.setPort(ports.get(0));
@@ -147,15 +142,15 @@ public class ApacheDSContainerTests {
server.afterPropertiesSet();
fail("Expected a RuntimeException to be thrown.");
}
catch (RuntimeException e){
catch (RuntimeException e) {
assertThat(e).hasMessage("Server startup failed");
assertThat(e).hasRootCauseInstanceOf(UnrecoverableKeyException.class);
}
}
/**
* This test starts an LDAP server using LDAPs (LDAP over SSL). A self-signed certificate is being used, which was
* previously generated with:
* This test starts an LDAP server using LDAPs (LDAP over SSL). A self-signed
* certificate is being used, which was previously generated with:
*
* <pre>
* {@code
@@ -168,14 +163,14 @@ public class ApacheDSContainerTests {
@Test
public void startWithLdapOverSsl() throws Exception {
final ClassPathResource keyStoreResource = new ClassPathResource("/org/springframework/security/ldap/server/spring.keystore");
final ClassPathResource keyStoreResource = new ClassPathResource(
"/org/springframework/security/ldap/server/spring.keystore");
final File temporaryKeyStoreFile = new File(temporaryFolder.getRoot(), "spring.keystore");
FileCopyUtils.copy(keyStoreResource.getInputStream(), new FileOutputStream(temporaryKeyStoreFile));
assertThat(temporaryKeyStoreFile).isFile();
ApacheDSContainer server = new ApacheDSContainer("dc=springframework,dc=org",
"classpath:test-server.ldif");
ApacheDSContainer server = new ApacheDSContainer("dc=springframework,dc=org", "classpath:test-server.ldif");
List<Integer> ports = getDefaultPorts(1);
server.setPort(ports.get(0));
@@ -216,8 +211,7 @@ public class ApacheDSContainerTests {
@Test
public void afterPropertiesSetWhenPortIsZeroThenRandomPortIsSelected() throws Exception {
ApacheDSContainer server = new ApacheDSContainer("dc=springframework,dc=org",
"classpath:test-server.ldif");
ApacheDSContainer server = new ApacheDSContainer("dc=springframework,dc=org", "classpath:test-server.ldif");
server.setPort(0);
try {
server.afterPropertiesSet();
@@ -229,4 +223,5 @@ public class ApacheDSContainerTests {
server.destroy();
}
}
}

View File

@@ -34,16 +34,17 @@ import static org.assertj.core.api.Assertions.assertThat;
public class ApacheDSEmbeddedLdifTests {
private static final String LDAP_ROOT = "ou=ssattributes,dc=springframework,dc=org";
private static final int LDAP_PORT = 52389;
private ApacheDSContainer server;
private SpringSecurityLdapTemplate ldapTemplate;
@Before
public void setUp() throws Exception {
// TODO: InMemoryXmlApplicationContext would be useful here, but it is not visible
this.server = new ApacheDSContainer(LDAP_ROOT,
"classpath:test-server-custom-attribute-types.ldif");
this.server = new ApacheDSContainer(LDAP_ROOT, "classpath:test-server-custom-attribute-types.ldif");
this.server.setPort(LDAP_PORT);
this.server.afterPropertiesSet();
@@ -68,10 +69,10 @@ public class ApacheDSEmbeddedLdifTests {
@Ignore // Not fixed yet
@Test // SEC-2387
public void customAttributeTypesShouldBeProperlyCreatedWhenLoadedFromLdif() {
assertThat(this.ldapTemplate.compare("uid=objectWithCustomAttribute1", "uid",
"objectWithCustomAttribute1")).isTrue();
assertThat(this.ldapTemplate.compare("uid=objectWithCustomAttribute1",
"customAttribute", "I am custom")).isTrue();
assertThat(this.ldapTemplate.compare("uid=objectWithCustomAttribute1", "uid", "objectWithCustomAttribute1"))
.isTrue();
assertThat(this.ldapTemplate.compare("uid=objectWithCustomAttribute1", "customAttribute", "I am custom"))
.isTrue();
}
}

View File

@@ -59,6 +59,7 @@ public class UnboundIdContainerLdifTests {
@Configuration
static class CustomLdifConfig {
private UnboundIdContainer container = new UnboundIdContainer("dc=springframework,dc=org",
"classpath:test-server.ldif");
@@ -70,14 +71,15 @@ public class UnboundIdContainerLdifTests {
@Bean
ContextSource contextSource(UnboundIdContainer container) {
return new DefaultSpringSecurityContextSource("ldap://127.0.0.1:"
+ container.getPort() + "/dc=springframework,dc=org");
return new DefaultSpringSecurityContextSource(
"ldap://127.0.0.1:" + container.getPort() + "/dc=springframework,dc=org");
}
@PreDestroy
void shutdown() {
this.container.stop();
}
}
@Test
@@ -93,6 +95,7 @@ public class UnboundIdContainerLdifTests {
@Configuration
static class WildcardLdifConfig {
private UnboundIdContainer container = new UnboundIdContainer("dc=springframework,dc=org",
"classpath*:test-server.ldif");
@@ -104,14 +107,15 @@ public class UnboundIdContainerLdifTests {
@Bean
ContextSource contextSource(UnboundIdContainer container) {
return new DefaultSpringSecurityContextSource("ldap://127.0.0.1:"
+ container.getPort() + "/dc=springframework,dc=org");
return new DefaultSpringSecurityContextSource(
"ldap://127.0.0.1:" + container.getPort() + "/dc=springframework,dc=org");
}
@PreDestroy
void shutdown() {
this.container.stop();
}
}
@Test
@@ -119,7 +123,8 @@ public class UnboundIdContainerLdifTests {
try {
appCtx = new AnnotationConfigApplicationContext(MalformedLdifConfig.class);
failBecauseExceptionWasNotThrown(IllegalStateException.class);
} catch (Exception e) {
}
catch (Exception e) {
assertThat(e.getCause()).isInstanceOf(IllegalStateException.class);
assertThat(e.getMessage()).contains("Unable to load LDIF classpath:test-server-malformed.txt");
}
@@ -127,6 +132,7 @@ public class UnboundIdContainerLdifTests {
@Configuration
static class MalformedLdifConfig {
private UnboundIdContainer container = new UnboundIdContainer("dc=springframework,dc=org",
"classpath:test-server-malformed.txt");
@@ -140,6 +146,7 @@ public class UnboundIdContainerLdifTests {
void shutdown() {
this.container.stop();
}
}
@Test
@@ -147,7 +154,8 @@ public class UnboundIdContainerLdifTests {
try {
appCtx = new AnnotationConfigApplicationContext(MissingLdifConfig.class);
failBecauseExceptionWasNotThrown(IllegalStateException.class);
} catch (Exception e) {
}
catch (Exception e) {
assertThat(e.getCause()).isInstanceOf(IllegalStateException.class);
assertThat(e.getMessage()).contains("Unable to load LDIF classpath:does-not-exist.ldif");
}
@@ -155,6 +163,7 @@ public class UnboundIdContainerLdifTests {
@Configuration
static class MissingLdifConfig {
private UnboundIdContainer container = new UnboundIdContainer("dc=springframework,dc=org",
"classpath:does-not-exist.ldif");
@@ -168,6 +177,7 @@ public class UnboundIdContainerLdifTests {
void shutdown() {
this.container.stop();
}
}
@Test
@@ -177,6 +187,7 @@ public class UnboundIdContainerLdifTests {
@Configuration
static class WildcardNoLdifConfig {
private UnboundIdContainer container = new UnboundIdContainer("dc=springframework,dc=org",
"classpath*:*.test.ldif");
@@ -190,5 +201,7 @@ public class UnboundIdContainerLdifTests {
void shutdown() {
this.container.stop();
}
}
}

View File

@@ -33,8 +33,7 @@ public class UnboundIdContainerTests {
@Test
public void startLdapServer() throws Exception {
UnboundIdContainer server = new UnboundIdContainer("dc=springframework,dc=org",
"classpath:test-server.ldif");
UnboundIdContainer server = new UnboundIdContainer("dc=springframework,dc=org", "classpath:test-server.ldif");
server.setApplicationContext(new GenericApplicationContext());
List<Integer> ports = getDefaultPorts(1);
server.setPort(ports.get(0));
@@ -42,7 +41,8 @@ public class UnboundIdContainerTests {
try {
server.afterPropertiesSet();
assertThat(server.getPort()).isEqualTo(ports.get(0));
} finally {
}
finally {
server.destroy();
}
}
@@ -55,7 +55,8 @@ public class UnboundIdContainerTests {
try {
server.afterPropertiesSet();
assertThat(server.getPort()).isNotEqualTo(0);
} finally {
}
finally {
server.destroy();
}
}
@@ -70,7 +71,8 @@ public class UnboundIdContainerTests {
availablePorts.add(socket.getLocalPort());
}
return availablePorts;
} finally {
}
finally {
for (ServerSocket conn : connections) {
conn.close();
}

View File

@@ -37,7 +37,6 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
/**
*
* @author Luke Taylor
* @author Eddú Meléndez
*/
@@ -48,6 +47,7 @@ public class DefaultLdapAuthoritiesPopulatorTests {
@Autowired
private ContextSource contextSource;
private DefaultLdapAuthoritiesPopulator populator;
// ~ Methods
@@ -64,11 +64,9 @@ public class DefaultLdapAuthoritiesPopulatorTests {
populator.setDefaultRole("ROLE_USER");
assertThat(populator.getContextSource()).isSameAs(this.contextSource);
DirContextAdapter ctx = new DirContextAdapter(
new DistinguishedName("cn=notfound"));
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("cn=notfound"));
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,
"notfound");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "notfound");
assertThat(authorities).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(authorities).contains("ROLE_USER")).isTrue();
}
@@ -78,8 +76,8 @@ public class DefaultLdapAuthoritiesPopulatorTests {
populator = new DefaultLdapAuthoritiesPopulator(this.contextSource, null);
populator.setDefaultRole("ROLE_USER");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(
new DirContextAdapter(new DistinguishedName("cn=notused")), "notused");
Collection<GrantedAuthority> authorities = populator
.getGrantedAuthorities(new DirContextAdapter(new DistinguishedName("cn=notused")), "notused");
assertThat(authorities).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(authorities).contains("ROLE_USER")).isTrue();
}
@@ -93,11 +91,10 @@ public class DefaultLdapAuthoritiesPopulatorTests {
populator.setConvertToUpperCase(true);
populator.setGroupSearchFilter("(member={0})");
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName(
"uid=ben,ou=people,dc=springframework,dc=org"));
DirContextAdapter ctx = new DirContextAdapter(
new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org"));
Set<String> authorities = AuthorityUtils.authorityListToSet(populator
.getGrantedAuthorities(ctx, "ben"));
Set<String> authorities = AuthorityUtils.authorityListToSet(populator.getGrantedAuthorities(ctx, "ben"));
assertThat(authorities).as("Should have 2 roles").hasSize(2);
@@ -111,11 +108,10 @@ public class DefaultLdapAuthoritiesPopulatorTests {
populator.setConvertToUpperCase(true);
populator.setGroupSearchFilter("(ou={1})");
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName(
"uid=ben,ou=people,dc=springframework,dc=org"));
DirContextAdapter ctx = new DirContextAdapter(
new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org"));
Set<String> authorities = AuthorityUtils.authorityListToSet(populator
.getGrantedAuthorities(ctx, "manager"));
Set<String> authorities = AuthorityUtils.authorityListToSet(populator.getGrantedAuthorities(ctx, "manager"));
assertThat(authorities).as("Should have 1 role").hasSize(1);
assertThat(authorities.contains("ROLE_MANAGER")).isTrue();
@@ -126,11 +122,10 @@ public class DefaultLdapAuthoritiesPopulatorTests {
populator.setGroupRoleAttribute("ou");
populator.setConvertToUpperCase(true);
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName(
"uid=ben,ou=people,dc=springframework,dc=org"));
DirContextAdapter ctx = new DirContextAdapter(
new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org"));
Set<String> authorities = AuthorityUtils.authorityListToSet(populator
.getGrantedAuthorities(ctx, "manager"));
Set<String> authorities = AuthorityUtils.authorityListToSet(populator.getGrantedAuthorities(ctx, "manager"));
assertThat(authorities).as("Should have 2 roles").hasSize(2);
assertThat(authorities.contains("ROLE_MANAGER")).isTrue();
@@ -143,11 +138,10 @@ public class DefaultLdapAuthoritiesPopulatorTests {
populator.setConvertToUpperCase(true);
populator.setSearchSubtree(true);
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName(
"uid=ben,ou=people,dc=springframework,dc=org"));
DirContextAdapter ctx = new DirContextAdapter(
new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org"));
Set<String> authorities = AuthorityUtils.authorityListToSet(populator
.getGrantedAuthorities(ctx, "manager"));
Set<String> authorities = AuthorityUtils.authorityListToSet(populator.getGrantedAuthorities(ctx, "manager"));
assertThat(authorities).as("Should have 3 roles").hasSize(3);
assertThat(authorities.contains("ROLE_MANAGER")).isTrue();
@@ -159,15 +153,13 @@ public class DefaultLdapAuthoritiesPopulatorTests {
public void extraRolesAreAdded() {
populator = new DefaultLdapAuthoritiesPopulator(this.contextSource, null) {
@Override
protected Set<GrantedAuthority> getAdditionalRoles(DirContextOperations user,
String username) {
return new HashSet<>(
AuthorityUtils.createAuthorityList("ROLE_EXTRA"));
protected Set<GrantedAuthority> getAdditionalRoles(DirContextOperations user, String username) {
return new HashSet<>(AuthorityUtils.createAuthorityList("ROLE_EXTRA"));
}
};
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(
new DirContextAdapter(new DistinguishedName("cn=notused")), "notused");
Collection<GrantedAuthority> authorities = populator
.getGrantedAuthorities(new DirContextAdapter(new DistinguishedName("cn=notused")), "notused");
assertThat(authorities).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(authorities).contains("ROLE_EXTRA")).isTrue();
}
@@ -178,11 +170,10 @@ public class DefaultLdapAuthoritiesPopulatorTests {
populator.setConvertToUpperCase(true);
populator.setGroupSearchFilter("(member={0})");
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName(
"cn=mouse\\, jerry,ou=people,dc=springframework,dc=org"));
DirContextAdapter ctx = new DirContextAdapter(
new DistinguishedName("cn=mouse\\, jerry,ou=people,dc=springframework,dc=org"));
Set<String> authorities = AuthorityUtils.authorityListToSet(populator
.getGrantedAuthorities(ctx, "notused"));
Set<String> authorities = AuthorityUtils.authorityListToSet(populator.getGrantedAuthorities(ctx, "notused"));
assertThat(authorities).as("Should have 1 role").hasSize(1);
assertThat(authorities.contains("ROLE_MANAGER")).isTrue();
@@ -196,8 +187,8 @@ public class DefaultLdapAuthoritiesPopulatorTests {
return new LdapAuthority(role, dn);
});
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName(
"cn=mouse\\, jerry,ou=people,dc=springframework,dc=org"));
DirContextAdapter ctx = new DirContextAdapter(
new DistinguishedName("cn=mouse\\, jerry,ou=people,dc=springframework,dc=org"));
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "notused");
@@ -208,4 +199,5 @@ public class DefaultLdapAuthoritiesPopulatorTests {
public void customAuthoritiesMappingFunctionThrowsIfNull() {
populator.setAuthorityMapper(null);
}
}

View File

@@ -44,7 +44,7 @@ import static org.assertj.core.api.Assertions.assertThatCode;
* @author Josh Cummings
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes=LdapUserDetailsManagerModifyPasswordTests.UnboundIdContainerConfiguration.class)
@ContextConfiguration(classes = LdapUserDetailsManagerModifyPasswordTests.UnboundIdContainerConfiguration.class)
public class LdapUserDetailsManagerModifyPasswordTests {
LdapUserDetailsManager userDetailsManager;
@@ -60,15 +60,14 @@ public class LdapUserDetailsManagerModifyPasswordTests {
}
@Test
@WithMockUser(username="bob", password="bobspassword", authorities="ROLE_USER")
@WithMockUser(username = "bob", password = "bobspassword", authorities = "ROLE_USER")
public void changePasswordWhenOldPasswordIsIncorrectThenThrowsException() {
assertThatCode(() ->
this.userDetailsManager.changePassword("wrongoldpassword", "bobsnewpassword"))
assertThatCode(() -> this.userDetailsManager.changePassword("wrongoldpassword", "bobsnewpassword"))
.isInstanceOf(BadCredentialsException.class);
}
@Test
@WithMockUser(username="bob", password="bobspassword", authorities="ROLE_USER")
@WithMockUser(username = "bob", password = "bobspassword", authorities = "ROLE_USER")
public void changePasswordWhenOldPasswordIsCorrectThenPasses() {
SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(this.contextSource);
@@ -76,11 +75,13 @@ public class LdapUserDetailsManagerModifyPasswordTests {
"bobsshinynewandformidablylongandnearlyimpossibletorememberthoughdemonstrablyhardtocrackduetoitshighlevelofentropypasswordofjustice");
assertThat(template.compare("uid=bob,ou=people", "userPassword",
"bobsshinynewandformidablylongandnearlyimpossibletorememberthoughdemonstrablyhardtocrackduetoitshighlevelofentropypasswordofjustice")).isTrue();
"bobsshinynewandformidablylongandnearlyimpossibletorememberthoughdemonstrablyhardtocrackduetoitshighlevelofentropypasswordofjustice"))
.isTrue();
}
@Configuration
static class UnboundIdContainerConfiguration {
private UnboundIdContainer container = new UnboundIdContainer("dc=springframework,dc=org",
"classpath:test-server.ldif");
@@ -92,13 +93,15 @@ public class LdapUserDetailsManagerModifyPasswordTests {
@Bean
ContextSource contextSource(UnboundIdContainer container) {
return new DefaultSpringSecurityContextSource("ldap://127.0.0.1:"
+ container.getPort() + "/dc=springframework,dc=org");
return new DefaultSpringSecurityContextSource(
"ldap://127.0.0.1:" + container.getPort() + "/dc=springframework,dc=org");
}
@PreDestroy
void shutdown() {
this.container.stop();
}
}
}

View File

@@ -52,8 +52,8 @@ public class LdapUserDetailsManagerTests {
@Autowired
private ContextSource contextSource;
private static final List<GrantedAuthority> TEST_AUTHORITIES = AuthorityUtils.createAuthorityList(
"ROLE_CLOWNS", "ROLE_ACROBATS");
private static final List<GrantedAuthority> TEST_AUTHORITIES = AuthorityUtils.createAuthorityList("ROLE_CLOWNS",
"ROLE_ACROBATS");
private LdapUserDetailsManager mgr;
@@ -76,8 +76,7 @@ public class LdapUserDetailsManagerTests {
group.setAttributeValue("objectclass", "groupOfNames");
group.setAttributeValue("cn", "clowns");
group.setAttributeValue("member",
"cn=nobody,ou=test people,dc=springframework,dc=org");
group.setAttributeValue("member", "cn=nobody,ou=test people,dc=springframework,dc=org");
template.bind("cn=clowns,ou=testgroups", group, null);
group.setAttributeValue("cn", "acrobats");
@@ -185,9 +184,7 @@ public class LdapUserDetailsManagerTests {
}
// Check that no authorities are left
assertThat(
mgr.getUserAuthorities(mgr.usernameMapper.buildDn("don"), "don")).hasSize(
0);
assertThat(mgr.getUserAuthorities(mgr.usernameMapper.buildDn("don"), "don")).hasSize(0);
}
@Test
@@ -203,13 +200,12 @@ public class LdapUserDetailsManagerTests {
mgr.createUser(p.createUserDetails());
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("johnyossarian",
"yossarianspassword", TEST_AUTHORITIES));
new UsernamePasswordAuthenticationToken("johnyossarian", "yossarianspassword", TEST_AUTHORITIES));
mgr.changePassword("yossarianspassword", "yossariansnewpassword");
assertThat(template.compare("uid=johnyossarian,ou=test people", "userPassword",
"yossariansnewpassword")).isTrue();
assertThat(template.compare("uid=johnyossarian,ou=test people", "userPassword", "yossariansnewpassword"))
.isTrue();
}
@Test(expected = BadCredentialsException.class)
@@ -225,9 +221,9 @@ public class LdapUserDetailsManagerTests {
mgr.createUser(p.createUserDetails());
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("johnyossarian",
"yossarianspassword", TEST_AUTHORITIES));
new UsernamePasswordAuthenticationToken("johnyossarian", "yossarianspassword", TEST_AUTHORITIES));
mgr.changePassword("wrongpassword", "yossariansnewpassword");
}
}

View File

@@ -43,12 +43,19 @@ public class NestedLdapAuthoritiesPopulatorTests {
@Autowired
private ContextSource contextSource;
private NestedLdapAuthoritiesPopulator populator;
private LdapAuthority javaDevelopers;
private LdapAuthority groovyDevelopers;
private LdapAuthority scalaDevelopers;
private LdapAuthority closureDevelopers;
private LdapAuthority jDevelopers;
private LdapAuthority circularJavaDevelopers;
// ~ Methods
@@ -56,15 +63,13 @@ public class NestedLdapAuthoritiesPopulatorTests {
@Before
public void setUp() {
populator = new NestedLdapAuthoritiesPopulator(this.contextSource,
"ou=jdeveloper");
populator = new NestedLdapAuthoritiesPopulator(this.contextSource, "ou=jdeveloper");
populator.setGroupSearchFilter("(member={0})");
populator.setIgnorePartialResultException(false);
populator.setRolePrefix("");
populator.setSearchSubtree(true);
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");
groovyDevelopers = new LdapAuthority("groovy-developers",
@@ -79,21 +84,17 @@ public class NestedLdapAuthoritiesPopulatorTests {
@Test
public void testScalaDudeJDevelopersAuthorities() {
DirContextAdapter ctx = new DirContextAdapter(
"uid=scaladude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,
"scaladude");
DirContextAdapter ctx = new DirContextAdapter("uid=scaladude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "scaladude");
assertThat(authorities).hasSize(5);
assertThat(authorities).isEqualTo(Arrays.asList(javaDevelopers, circularJavaDevelopers,
scalaDevelopers, groovyDevelopers, jDevelopers));
assertThat(authorities).isEqualTo(
Arrays.asList(javaDevelopers, circularJavaDevelopers, scalaDevelopers, groovyDevelopers, jDevelopers));
}
@Test
public void testJavaDudeJDevelopersAuthorities() {
DirContextAdapter ctx = new DirContextAdapter(
"uid=javadude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,
"javadude");
DirContextAdapter ctx = new DirContextAdapter("uid=javadude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "javadude");
assertThat(authorities).hasSize(4);
assertThat(authorities).contains(javaDevelopers);
}
@@ -101,36 +102,30 @@ public class NestedLdapAuthoritiesPopulatorTests {
@Test
public void testScalaDudeJDevelopersAuthoritiesWithSearchLimit() {
populator.setMaxSearchDepth(1);
DirContextAdapter ctx = new DirContextAdapter(
"uid=scaladude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,
"scaladude");
DirContextAdapter ctx = new DirContextAdapter("uid=scaladude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "scaladude");
assertThat(authorities).hasSize(1);
assertThat(authorities).isEqualTo(Arrays.asList(scalaDevelopers));
}
@Test
public void testGroovyDudeJDevelopersAuthorities() {
DirContextAdapter ctx = new DirContextAdapter(
"uid=groovydude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,
"groovydude");
DirContextAdapter ctx = new DirContextAdapter("uid=groovydude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "groovydude");
assertThat(authorities).hasSize(4);
assertThat(authorities).isEqualTo(Arrays.asList(javaDevelopers, circularJavaDevelopers, groovyDevelopers,
jDevelopers));
assertThat(authorities)
.isEqualTo(Arrays.asList(javaDevelopers, circularJavaDevelopers, groovyDevelopers, jDevelopers));
}
@Test
public void testClosureDudeJDevelopersWithMembershipAsAttributeValues() {
populator.setAttributeNames(new HashSet(Arrays.asList("member")));
DirContextAdapter ctx = new DirContextAdapter(
"uid=closuredude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,
"closuredude");
DirContextAdapter ctx = new DirContextAdapter("uid=closuredude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "closuredude");
assertThat(authorities).hasSize(5);
assertThat(authorities).isEqualTo(Arrays.asList(javaDevelopers, circularJavaDevelopers,
closureDevelopers, groovyDevelopers, jDevelopers));
assertThat(authorities).isEqualTo(Arrays.asList(javaDevelopers, circularJavaDevelopers, closureDevelopers,
groovyDevelopers, jDevelopers));
LdapAuthority[] ldapAuthorities = authorities.toArray(new LdapAuthority[0]);
assertThat(ldapAuthorities).hasSize(5);
@@ -138,15 +133,16 @@ public class NestedLdapAuthoritiesPopulatorTests {
assertThat(ldapAuthorities[0].getAttributes().containsKey("member")).isTrue();
assertThat(ldapAuthorities[0].getAttributes().get("member")).isNotNull();
assertThat(ldapAuthorities[0].getAttributes().get("member")).hasSize(3);
assertThat(ldapAuthorities[0].getFirstAttributeValue("member")).isEqualTo("cn=groovy-developers,ou=jdeveloper,dc=springframework,dc=org");
assertThat(ldapAuthorities[0].getFirstAttributeValue("member"))
.isEqualTo("cn=groovy-developers,ou=jdeveloper,dc=springframework,dc=org");
// java group
assertThat(ldapAuthorities[1].getAttributes().containsKey("member")).isTrue();
assertThat(ldapAuthorities[1].getAttributes().get("member")).isNotNull();
assertThat(ldapAuthorities[1].getAttributes().get("member")).hasSize(3);
assertThat(groovyDevelopers.getDn()).isEqualTo(ldapAuthorities[1].getFirstAttributeValue("member"));
assertThat(ldapAuthorities[2]
.getAttributes().get("member")).contains("uid=closuredude,ou=people,dc=springframework,dc=org");
assertThat(ldapAuthorities[2].getAttributes().get("member"))
.contains("uid=closuredude,ou=people,dc=springframework,dc=org");
// test non existent attribute
assertThat(ldapAuthorities[2].getFirstAttributeValue("test")).isNull();
@@ -155,4 +151,5 @@ public class NestedLdapAuthoritiesPopulatorTests {
// test role name
assertThat(ldapAuthorities[3].getAuthority()).isEqualTo(groovyDevelopers.getAuthority());
}
}