1
0
mirror of synced 2026-05-22 21:33:16 +00:00

Always use 'this.' when accessing fields

Apply an Eclipse cleanup rules to ensure that fields are always accessed
using `this.`. This aligns with the style used by Spring Framework and
helps users quickly see the difference between a local and member
variable.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-07-26 11:51:05 -07:00
committed by Rob Winch
parent 6894ff5d12
commit 8866fa6fb0
793 changed files with 8689 additions and 8459 deletions
@@ -55,27 +55,27 @@ public class SpringSecurityLdapTemplateITests {
@Before
public void setUp() {
template = new SpringSecurityLdapTemplate(this.contextSource);
this.template = new SpringSecurityLdapTemplate(this.contextSource);
}
@Test
public void compareOfCorrectValueSucceeds() {
assertThat(template.compare("uid=bob,ou=people", "uid", "bob")).isTrue();
assertThat(this.template.compare("uid=bob,ou=people", "uid", "bob")).isTrue();
}
@Test
public void compareOfCorrectByteValueSucceeds() {
assertThat(template.compare("uid=bob,ou=people", "userPassword", Utf8.encode("bobspassword"))).isTrue();
assertThat(this.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(this.template.compare("uid=bob,ou=people", "userPassword", Utf8.encode("wrongvalue"))).isFalse();
}
@Test
public void compareOfWrongValueFails() {
assertThat(template.compare("uid=bob,ou=people", "uid", "wrongvalue")).isFalse();
assertThat(this.template.compare("uid=bob,ou=people", "uid", "wrongvalue")).isFalse();
}
// @Test
@@ -91,7 +91,7 @@ public class SpringSecurityLdapTemplateITests {
@Test
public void namingExceptionIsTranslatedCorrectly() {
try {
template.executeReadOnly((ContextExecutor) dirContext -> {
this.template.executeReadOnly((ContextExecutor) dirContext -> {
throw new NamingException();
});
fail("Expected UncategorizedLdapException on NamingException");
@@ -104,7 +104,7 @@ 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})",
Set<String> values = this.template.searchForSingleAttributeValues("ou=groups", "(member={0})",
new String[] { param }, "ou");
assertThat(values).as("Expected 3 results from search").hasSize(3);
@@ -115,7 +115,7 @@ public class SpringSecurityLdapTemplateITests {
@Test
public void testMultiAttributeRetrievalWithNullAttributeNames() {
Set<Map<String, List<String>>> values = template.searchForMultipleAttributeValues("ou=people", "(uid={0})",
Set<Map<String, List<String>>> values = this.template.searchForMultipleAttributeValues("ou=people", "(uid={0})",
new String[] { "bob" }, null);
assertThat(values).hasSize(1);
Map<String, List<String>> record = values.iterator().next();
@@ -128,7 +128,7 @@ public class SpringSecurityLdapTemplateITests {
@Test
public void testMultiAttributeRetrievalWithZeroLengthAttributeNames() {
Set<Map<String, List<String>>> values = template.searchForMultipleAttributeValues("ou=people", "(uid={0})",
Set<Map<String, List<String>>> values = this.template.searchForMultipleAttributeValues("ou=people", "(uid={0})",
new String[] { "bob" }, new String[0]);
assertThat(values).hasSize(1);
Map<String, List<String>> record = values.iterator().next();
@@ -141,7 +141,7 @@ public class SpringSecurityLdapTemplateITests {
@Test
public void testMultiAttributeRetrievalWithSpecifiedAttributeNames() {
Set<Map<String, List<String>>> values = template.searchForMultipleAttributeValues("ou=people", "(uid={0})",
Set<Map<String, List<String>>> values = this.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();
@@ -164,7 +164,7 @@ 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})",
Set<String> values = this.template.searchForSingleAttributeValues("ou=groups", "(member={0})",
new String[] { param }, "mail");
assertThat(values).isEmpty();
@@ -174,7 +174,7 @@ 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})",
Set<String> values = this.template.searchForSingleAttributeValues("ou=groups", "(member={0})",
new String[] { param }, "cn");
assertThat(values).hasSize(1);
@@ -205,7 +205,7 @@ public class SpringSecurityLdapTemplateITests {
public void searchForSingleEntryWithEscapedCharsInDnSucceeds() {
String param = "mouse, jerry";
template.searchForSingleEntry("ou=people", "(cn={0})", new String[] { param });
this.template.searchForSingleEntry("ou=people", "(cn={0})", new String[] { param });
}
}
@@ -59,29 +59,30 @@ public class PasswordComparisonAuthenticatorTests {
@Before
public void setUp() {
authenticator = new PasswordComparisonAuthenticator(this.contextSource);
authenticator.setPasswordEncoder(NoOpPasswordEncoder.getInstance());
authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
bob = new UsernamePasswordAuthenticationToken("bob", "bobspassword");
ben = new UsernamePasswordAuthenticationToken("ben", "benspassword");
this.authenticator = new PasswordComparisonAuthenticator(this.contextSource);
this.authenticator.setPasswordEncoder(NoOpPasswordEncoder.getInstance());
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
this.bob = new UsernamePasswordAuthenticationToken("bob", "bobspassword");
this.ben = new UsernamePasswordAuthenticationToken("ben", "benspassword");
}
@Test
public void testAllAttributesAreRetrievedByDefault() {
DirContextAdapter user = (DirContextAdapter) authenticator.authenticate(bob);
DirContextAdapter user = (DirContextAdapter) this.authenticator.authenticate(this.bob);
// System.out.println(user.getAttributes().toString());
assertThat(user.getAttributes().size()).withFailMessage("User should have 5 attributes").isEqualTo(5);
}
@Test
public void testFailedSearchGivesUserNotFoundException() throws Exception {
authenticator = new PasswordComparisonAuthenticator(this.contextSource);
assertThat(authenticator.getUserDns("Bob")).withFailMessage("User DN matches shouldn't be available").isEmpty();
authenticator.setUserSearch(new MockUserSearch(null));
authenticator.afterPropertiesSet();
this.authenticator = new PasswordComparisonAuthenticator(this.contextSource);
assertThat(this.authenticator.getUserDns("Bob")).withFailMessage("User DN matches shouldn't be available")
.isEmpty();
this.authenticator.setUserSearch(new MockUserSearch(null));
this.authenticator.afterPropertiesSet();
try {
authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass"));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass"));
fail("Expected exception on failed user search");
}
catch (UsernameNotFoundException expected) {
@@ -91,69 +92,70 @@ public class PasswordComparisonAuthenticatorTests {
@Test(expected = BadCredentialsException.class)
public void testLdapPasswordCompareFailsWithWrongPassword() {
// Don't retrieve the password
authenticator.setUserAttributes(new String[] { "uid", "cn", "sn" });
authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpass"));
this.authenticator.setUserAttributes(new String[] { "uid", "cn", "sn" });
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpass"));
}
@Test
public void testMultipleDnPatternsWorkOk() {
authenticator.setUserDnPatterns(new String[] { "uid={0},ou=nonexistent", "uid={0},ou=people" });
authenticator.authenticate(bob);
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=nonexistent", "uid={0},ou=people" });
this.authenticator.authenticate(this.bob);
}
@Test
public void testOnlySpecifiedAttributesAreRetrieved() {
authenticator.setUserAttributes(new String[] { "uid", "userPassword" });
this.authenticator.setUserAttributes(new String[] { "uid", "userPassword" });
DirContextAdapter user = (DirContextAdapter) authenticator.authenticate(bob);
DirContextAdapter user = (DirContextAdapter) this.authenticator.authenticate(this.bob);
assertThat(user.getAttributes().size()).withFailMessage("Should have retrieved 2 attribute (uid)").isEqualTo(2);
}
@Test
public void testLdapCompareSucceedsWithCorrectPassword() {
// Don't retrieve the password
authenticator.setUserAttributes(new String[] { "uid" });
authenticator.authenticate(bob);
this.authenticator.setUserAttributes(new String[] { "uid" });
this.authenticator.authenticate(this.bob);
}
@Test
public void testLdapCompareSucceedsWithShaEncodedPassword() {
// Don't retrieve the password
authenticator.setUserAttributes(new String[] { "uid" });
authenticator.setPasswordEncoder(new LdapShaPasswordEncoder(KeyGenerators.shared(0)));
authenticator.setUsePasswordAttrCompare(false);
authenticator.authenticate(ben);
this.authenticator.setUserAttributes(new String[] { "uid" });
this.authenticator.setPasswordEncoder(new LdapShaPasswordEncoder(KeyGenerators.shared(0)));
this.authenticator.setUsePasswordAttrCompare(false);
this.authenticator.authenticate(this.ben);
}
@Test(expected = IllegalArgumentException.class)
public void testPasswordEncoderCantBeNull() {
authenticator.setPasswordEncoder(null);
this.authenticator.setPasswordEncoder(null);
}
@Test
public void testUseOfDifferentPasswordAttributeSucceeds() {
authenticator.setPasswordAttributeName("uid");
authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "bob"));
this.authenticator.setPasswordAttributeName("uid");
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "bob"));
}
@Test
public void testLdapCompareWithDifferentPasswordAttributeSucceeds() {
authenticator.setUserAttributes(new String[] { "uid" });
authenticator.setPasswordAttributeName("cn");
authenticator.authenticate(new UsernamePasswordAuthenticationToken("ben", "Ben Alex"));
this.authenticator.setUserAttributes(new String[] { "uid" });
this.authenticator.setPasswordAttributeName("cn");
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("ben", "Ben Alex"));
}
@Test
public void testWithUserSearch() {
authenticator = new PasswordComparisonAuthenticator(this.contextSource);
authenticator.setPasswordEncoder(NoOpPasswordEncoder.getInstance());
assertThat(authenticator.getUserDns("Bob")).withFailMessage("User DN matches shouldn't be available").isEmpty();
this.authenticator = new PasswordComparisonAuthenticator(this.contextSource);
this.authenticator.setPasswordEncoder(NoOpPasswordEncoder.getInstance());
assertThat(this.authenticator.getUserDns("Bob")).withFailMessage("User DN matches shouldn't be available")
.isEmpty();
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"));
this.authenticator.setUserSearch(new MockUserSearch(ctx));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("shouldntbeused", "bobspassword"));
}
}
@@ -125,7 +125,7 @@ public class ApacheDSContainerTests {
public void startWithLdapOverSslWithWrongPassword() throws Exception {
final ClassPathResource keyStoreResource = new ClassPathResource(
"/org/springframework/security/ldap/server/spring.keystore");
final File temporaryKeyStoreFile = new File(temporaryFolder.getRoot(), "spring.keystore");
final File temporaryKeyStoreFile = new File(this.temporaryFolder.getRoot(), "spring.keystore");
FileCopyUtils.copy(keyStoreResource.getInputStream(), new FileOutputStream(temporaryKeyStoreFile));
assertThat(temporaryKeyStoreFile).isFile();
@@ -166,7 +166,7 @@ public class ApacheDSContainerTests {
final ClassPathResource keyStoreResource = new ClassPathResource(
"/org/springframework/security/ldap/server/spring.keystore");
final File temporaryKeyStoreFile = new File(temporaryFolder.getRoot(), "spring.keystore");
final File temporaryKeyStoreFile = new File(this.temporaryFolder.getRoot(), "spring.keystore");
FileCopyUtils.copy(keyStoreResource.getInputStream(), new FileOutputStream(temporaryKeyStoreFile));
assertThat(temporaryKeyStoreFile).isFile();
@@ -41,17 +41,17 @@ public class UnboundIdContainerLdifTests {
@After
public void closeAppContext() {
if (appCtx != null) {
appCtx.close();
appCtx = null;
if (this.appCtx != null) {
this.appCtx.close();
this.appCtx = null;
}
}
@Test
public void unboundIdContainerWhenCustomLdifNameThenLdifLoaded() {
appCtx = new AnnotationConfigApplicationContext(CustomLdifConfig.class);
this.appCtx = new AnnotationConfigApplicationContext(CustomLdifConfig.class);
DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) appCtx
DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) this.appCtx
.getBean(ContextSource.class);
SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(contextSource);
@@ -85,9 +85,9 @@ public class UnboundIdContainerLdifTests {
@Test
public void unboundIdContainerWhenWildcardLdifNameThenLdifLoaded() {
appCtx = new AnnotationConfigApplicationContext(WildcardLdifConfig.class);
this.appCtx = new AnnotationConfigApplicationContext(WildcardLdifConfig.class);
DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) appCtx
DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) this.appCtx
.getBean(ContextSource.class);
SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(contextSource);
@@ -122,7 +122,7 @@ public class UnboundIdContainerLdifTests {
@Test
public void unboundIdContainerWhenMalformedLdifThenException() {
try {
appCtx = new AnnotationConfigApplicationContext(MalformedLdifConfig.class);
this.appCtx = new AnnotationConfigApplicationContext(MalformedLdifConfig.class);
failBecauseExceptionWasNotThrown(IllegalStateException.class);
}
catch (Exception e) {
@@ -153,7 +153,7 @@ public class UnboundIdContainerLdifTests {
@Test
public void unboundIdContainerWhenMissingLdifThenException() {
try {
appCtx = new AnnotationConfigApplicationContext(MissingLdifConfig.class);
this.appCtx = new AnnotationConfigApplicationContext(MissingLdifConfig.class);
failBecauseExceptionWasNotThrown(IllegalStateException.class);
}
catch (Exception e) {
@@ -54,28 +54,28 @@ public class DefaultLdapAuthoritiesPopulatorTests {
@Before
public void setUp() {
populator = new DefaultLdapAuthoritiesPopulator(this.contextSource, "ou=groups");
populator.setIgnorePartialResultException(false);
this.populator = new DefaultLdapAuthoritiesPopulator(this.contextSource, "ou=groups");
this.populator.setIgnorePartialResultException(false);
}
@Test
public void defaultRoleIsAssignedWhenSet() {
populator.setDefaultRole("ROLE_USER");
assertThat(populator.getContextSource()).isSameAs(this.contextSource);
this.populator.setDefaultRole("ROLE_USER");
assertThat(this.populator.getContextSource()).isSameAs(this.contextSource);
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("cn=notfound"));
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "notfound");
Collection<GrantedAuthority> authorities = this.populator.getGrantedAuthorities(ctx, "notfound");
assertThat(authorities).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(authorities).contains("ROLE_USER")).isTrue();
}
@Test
public void nullSearchBaseIsAccepted() {
populator = new DefaultLdapAuthoritiesPopulator(this.contextSource, null);
populator.setDefaultRole("ROLE_USER");
this.populator = new DefaultLdapAuthoritiesPopulator(this.contextSource, null);
this.populator.setDefaultRole("ROLE_USER");
Collection<GrantedAuthority> authorities = populator
Collection<GrantedAuthority> authorities = this.populator
.getGrantedAuthorities(new DirContextAdapter(new DistinguishedName("cn=notused")), "notused");
assertThat(authorities).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(authorities).contains("ROLE_USER")).isTrue();
@@ -83,17 +83,17 @@ public class DefaultLdapAuthoritiesPopulatorTests {
@Test
public void groupSearchReturnsExpectedRoles() {
populator.setRolePrefix("ROLE_");
populator.setGroupRoleAttribute("ou");
populator.setSearchSubtree(true);
populator.setSearchSubtree(false);
populator.setConvertToUpperCase(true);
populator.setGroupSearchFilter("(member={0})");
this.populator.setRolePrefix("ROLE_");
this.populator.setGroupRoleAttribute("ou");
this.populator.setSearchSubtree(true);
this.populator.setSearchSubtree(false);
this.populator.setConvertToUpperCase(true);
this.populator.setGroupSearchFilter("(member={0})");
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(this.populator.getGrantedAuthorities(ctx, "ben"));
assertThat(authorities).as("Should have 2 roles").hasSize(2);
@@ -103,14 +103,15 @@ public class DefaultLdapAuthoritiesPopulatorTests {
@Test
public void useOfUsernameParameterReturnsExpectedRoles() {
populator.setGroupRoleAttribute("ou");
populator.setConvertToUpperCase(true);
populator.setGroupSearchFilter("(ou={1})");
this.populator.setGroupRoleAttribute("ou");
this.populator.setConvertToUpperCase(true);
this.populator.setGroupSearchFilter("(ou={1})");
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(this.populator.getGrantedAuthorities(ctx, "manager"));
assertThat(authorities).as("Should have 1 role").hasSize(1);
assertThat(authorities.contains("ROLE_MANAGER")).isTrue();
@@ -118,13 +119,14 @@ public class DefaultLdapAuthoritiesPopulatorTests {
@Test
public void subGroupRolesAreNotFoundByDefault() {
populator.setGroupRoleAttribute("ou");
populator.setConvertToUpperCase(true);
this.populator.setGroupRoleAttribute("ou");
this.populator.setConvertToUpperCase(true);
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(this.populator.getGrantedAuthorities(ctx, "manager"));
assertThat(authorities).as("Should have 2 roles").hasSize(2);
assertThat(authorities.contains("ROLE_MANAGER")).isTrue();
@@ -133,14 +135,15 @@ public class DefaultLdapAuthoritiesPopulatorTests {
@Test
public void subGroupRolesAreFoundWhenSubtreeSearchIsEnabled() {
populator.setGroupRoleAttribute("ou");
populator.setConvertToUpperCase(true);
populator.setSearchSubtree(true);
this.populator.setGroupRoleAttribute("ou");
this.populator.setConvertToUpperCase(true);
this.populator.setSearchSubtree(true);
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(this.populator.getGrantedAuthorities(ctx, "manager"));
assertThat(authorities).as("Should have 3 roles").hasSize(3);
assertThat(authorities.contains("ROLE_MANAGER")).isTrue();
@@ -150,14 +153,14 @@ public class DefaultLdapAuthoritiesPopulatorTests {
@Test
public void extraRolesAreAdded() {
populator = new DefaultLdapAuthoritiesPopulator(this.contextSource, null) {
this.populator = new DefaultLdapAuthoritiesPopulator(this.contextSource, null) {
@Override
protected Set<GrantedAuthority> getAdditionalRoles(DirContextOperations user, String username) {
return new HashSet<>(AuthorityUtils.createAuthorityList("ROLE_EXTRA"));
}
};
Collection<GrantedAuthority> authorities = populator
Collection<GrantedAuthority> authorities = this.populator
.getGrantedAuthorities(new DirContextAdapter(new DistinguishedName("cn=notused")), "notused");
assertThat(authorities).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(authorities).contains("ROLE_EXTRA")).isTrue();
@@ -165,14 +168,15 @@ public class DefaultLdapAuthoritiesPopulatorTests {
@Test
public void userDnWithEscapedCharacterParameterReturnsExpectedRoles() {
populator.setGroupRoleAttribute("ou");
populator.setConvertToUpperCase(true);
populator.setGroupSearchFilter("(member={0})");
this.populator.setGroupRoleAttribute("ou");
this.populator.setConvertToUpperCase(true);
this.populator.setGroupSearchFilter("(member={0})");
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(this.populator.getGrantedAuthorities(ctx, "notused"));
assertThat(authorities).as("Should have 1 role").hasSize(1);
assertThat(authorities.contains("ROLE_MANAGER")).isTrue();
@@ -180,23 +184,23 @@ public class DefaultLdapAuthoritiesPopulatorTests {
@Test
public void customAuthoritiesMappingFunction() {
populator.setAuthorityMapper(record -> {
this.populator.setAuthorityMapper(record -> {
String dn = record.get(SpringSecurityLdapTemplate.DN_KEY).get(0);
String role = record.get(populator.getGroupRoleAttribute()).get(0);
String role = record.get(this.populator.getGroupRoleAttribute()).get(0);
return new LdapAuthority(role, dn);
});
DirContextAdapter ctx = new DirContextAdapter(
new DistinguishedName("cn=mouse\\, jerry,ou=people,dc=springframework,dc=org"));
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "notused");
Collection<GrantedAuthority> authorities = this.populator.getGrantedAuthorities(ctx, "notused");
assertThat(authorities).allMatch(LdapAuthority.class::isInstance);
}
@Test(expected = IllegalArgumentException.class)
public void customAuthoritiesMappingFunctionThrowsIfNull() {
populator.setAuthorityMapper(null);
this.populator.setAuthorityMapper(null);
}
}
@@ -61,32 +61,32 @@ public class LdapUserDetailsManagerTests {
@Before
public void setUp() {
mgr = new LdapUserDetailsManager(this.contextSource);
template = new SpringSecurityLdapTemplate(this.contextSource);
this.mgr = new LdapUserDetailsManager(this.contextSource);
this.template = new SpringSecurityLdapTemplate(this.contextSource);
DirContextAdapter ctx = new DirContextAdapter();
ctx.setAttributeValue("objectclass", "organizationalUnit");
ctx.setAttributeValue("ou", "test people");
template.bind("ou=test people", ctx, null);
this.template.bind("ou=test people", ctx, null);
ctx.setAttributeValue("ou", "testgroups");
template.bind("ou=testgroups", ctx, null);
this.template.bind("ou=testgroups", ctx, null);
DirContextAdapter group = new DirContextAdapter();
group.setAttributeValue("objectclass", "groupOfNames");
group.setAttributeValue("cn", "clowns");
group.setAttributeValue("member", "cn=nobody,ou=test people,dc=springframework,dc=org");
template.bind("cn=clowns,ou=testgroups", group, null);
this.template.bind("cn=clowns,ou=testgroups", group, null);
group.setAttributeValue("cn", "acrobats");
template.bind("cn=acrobats,ou=testgroups", group, null);
this.template.bind("cn=acrobats,ou=testgroups", group, null);
mgr.setUsernameMapper(new DefaultLdapUsernameToDnMapper("ou=test people", "uid"));
mgr.setGroupSearchBase("ou=testgroups");
mgr.setGroupRoleAttributeName("cn");
mgr.setGroupMemberAttributeName("member");
mgr.setUserDetailsMapper(new PersonContextMapper());
this.mgr.setUsernameMapper(new DefaultLdapUsernameToDnMapper("ou=test people", "uid"));
this.mgr.setGroupSearchBase("ou=testgroups");
this.mgr.setGroupRoleAttributeName("cn");
this.mgr.setGroupMemberAttributeName("member");
this.mgr.setUserDetailsMapper(new PersonContextMapper());
}
@After
@@ -100,17 +100,17 @@ public class LdapUserDetailsManagerTests {
// template.unbind((String) people.next() + ",ou=testpeople");
// }
template.unbind("ou=test people", true);
template.unbind("ou=testgroups", true);
this.template.unbind("ou=test people", true);
this.template.unbind("ou=testgroups", true);
SecurityContextHolder.clearContext();
}
@Test
public void testLoadUserByUsernameReturnsCorrectData() {
mgr.setUsernameMapper(new DefaultLdapUsernameToDnMapper("ou=people", "uid"));
mgr.setGroupSearchBase("ou=groups");
LdapUserDetails bob = (LdapUserDetails) mgr.loadUserByUsername("bob");
this.mgr.setUsernameMapper(new DefaultLdapUsernameToDnMapper("ou=people", "uid"));
this.mgr.setGroupSearchBase("ou=groups");
LdapUserDetails bob = (LdapUserDetails) this.mgr.loadUserByUsername("bob");
assertThat(bob.getUsername()).isEqualTo("bob");
assertThat(bob.getDn()).isEqualTo("uid=bob,ou=people,dc=springframework,dc=org");
assertThat(bob.getPassword()).isEqualTo("bobspassword");
@@ -120,18 +120,18 @@ public class LdapUserDetailsManagerTests {
@Test(expected = UsernameNotFoundException.class)
public void testLoadingInvalidUsernameThrowsUsernameNotFoundException() {
mgr.loadUserByUsername("jim");
this.mgr.loadUserByUsername("jim");
}
@Test
public void testUserExistsReturnsTrueForValidUser() {
mgr.setUsernameMapper(new DefaultLdapUsernameToDnMapper("ou=people", "uid"));
assertThat(mgr.userExists("bob")).isTrue();
this.mgr.setUsernameMapper(new DefaultLdapUsernameToDnMapper("ou=people", "uid"));
assertThat(this.mgr.userExists("bob")).isTrue();
}
@Test
public void testUserExistsReturnsFalseForInValidUser() {
assertThat(mgr.userExists("jim")).isFalse();
assertThat(this.mgr.userExists("jim")).isFalse();
}
@Test
@@ -154,7 +154,7 @@ public class LdapUserDetailsManagerTests {
p.setAuthorities(TEST_AUTHORITIES);
mgr.createUser(p.createUserDetails());
this.mgr.createUser(p.createUserDetails());
}
@Test
@@ -166,17 +166,17 @@ public class LdapUserDetailsManagerTests {
p.setUid("don");
p.setAuthorities(TEST_AUTHORITIES);
mgr.createUser(p.createUserDetails());
mgr.setUserDetailsMapper(new InetOrgPersonContextMapper());
this.mgr.createUser(p.createUserDetails());
this.mgr.setUserDetailsMapper(new InetOrgPersonContextMapper());
InetOrgPerson don = (InetOrgPerson) mgr.loadUserByUsername("don");
InetOrgPerson don = (InetOrgPerson) this.mgr.loadUserByUsername("don");
assertThat(don.getAuthorities()).hasSize(2);
mgr.deleteUser("don");
this.mgr.deleteUser("don");
try {
mgr.loadUserByUsername("don");
this.mgr.loadUserByUsername("don");
fail("Expected UsernameNotFoundException after deleting user");
}
catch (UsernameNotFoundException expected) {
@@ -184,7 +184,7 @@ public class LdapUserDetailsManagerTests {
}
// Check that no authorities are left
assertThat(mgr.getUserAuthorities(mgr.usernameMapper.buildDn("don"), "don")).hasSize(0);
assertThat(this.mgr.getUserAuthorities(this.mgr.usernameMapper.buildDn("don"), "don")).hasSize(0);
}
@Test
@@ -197,14 +197,14 @@ public class LdapUserDetailsManagerTests {
p.setPassword("yossarianspassword");
p.setAuthorities(TEST_AUTHORITIES);
mgr.createUser(p.createUserDetails());
this.mgr.createUser(p.createUserDetails());
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("johnyossarian", "yossarianspassword", TEST_AUTHORITIES));
mgr.changePassword("yossarianspassword", "yossariansnewpassword");
this.mgr.changePassword("yossarianspassword", "yossariansnewpassword");
assertThat(template.compare("uid=johnyossarian,ou=test people", "userPassword", "yossariansnewpassword"))
assertThat(this.template.compare("uid=johnyossarian,ou=test people", "userPassword", "yossariansnewpassword"))
.isTrue();
}
@@ -218,12 +218,12 @@ public class LdapUserDetailsManagerTests {
p.setPassword("yossarianspassword");
p.setAuthorities(TEST_AUTHORITIES);
mgr.createUser(p.createUserDetails());
this.mgr.createUser(p.createUserDetails());
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("johnyossarian", "yossarianspassword", TEST_AUTHORITIES));
mgr.changePassword("wrongpassword", "yossariansnewpassword");
this.mgr.changePassword("wrongpassword", "yossariansnewpassword");
}
}
@@ -60,69 +60,69 @@ public class NestedLdapAuthoritiesPopulatorTests {
@Before
public void setUp() {
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");
javaDevelopers = new LdapAuthority("java-developers",
this.populator = new NestedLdapAuthoritiesPopulator(this.contextSource, "ou=jdeveloper");
this.populator.setGroupSearchFilter("(member={0})");
this.populator.setIgnorePartialResultException(false);
this.populator.setRolePrefix("");
this.populator.setSearchSubtree(true);
this.populator.setConvertToUpperCase(false);
this.jDevelopers = new LdapAuthority("j-developers", "cn=j-developers,ou=jdeveloper,dc=springframework,dc=org");
this.javaDevelopers = new LdapAuthority("java-developers",
"cn=java-developers,ou=jdeveloper,dc=springframework,dc=org");
groovyDevelopers = new LdapAuthority("groovy-developers",
this.groovyDevelopers = new LdapAuthority("groovy-developers",
"cn=groovy-developers,ou=jdeveloper,dc=springframework,dc=org");
scalaDevelopers = new LdapAuthority("scala-developers",
this.scalaDevelopers = new LdapAuthority("scala-developers",
"cn=scala-developers,ou=jdeveloper,dc=springframework,dc=org");
closureDevelopers = new LdapAuthority("closure-developers",
this.closureDevelopers = new LdapAuthority("closure-developers",
"cn=closure-developers,ou=jdeveloper,dc=springframework,dc=org");
circularJavaDevelopers = new LdapAuthority("circular-java-developers",
this.circularJavaDevelopers = new LdapAuthority("circular-java-developers",
"cn=circular-java-developers,ou=jdeveloper,dc=springframework,dc=org");
}
@Test
public void testScalaDudeJDevelopersAuthorities() {
DirContextAdapter ctx = new DirContextAdapter("uid=scaladude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "scaladude");
Collection<GrantedAuthority> authorities = this.populator.getGrantedAuthorities(ctx, "scaladude");
assertThat(authorities).hasSize(5);
assertThat(authorities).isEqualTo(
Arrays.asList(javaDevelopers, circularJavaDevelopers, scalaDevelopers, groovyDevelopers, jDevelopers));
assertThat(authorities).isEqualTo(Arrays.asList(this.javaDevelopers, this.circularJavaDevelopers,
this.scalaDevelopers, this.groovyDevelopers, this.jDevelopers));
}
@Test
public void testJavaDudeJDevelopersAuthorities() {
DirContextAdapter ctx = new DirContextAdapter("uid=javadude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "javadude");
Collection<GrantedAuthority> authorities = this.populator.getGrantedAuthorities(ctx, "javadude");
assertThat(authorities).hasSize(4);
assertThat(authorities).contains(javaDevelopers);
assertThat(authorities).contains(this.javaDevelopers);
}
@Test
public void testScalaDudeJDevelopersAuthoritiesWithSearchLimit() {
populator.setMaxSearchDepth(1);
this.populator.setMaxSearchDepth(1);
DirContextAdapter ctx = new DirContextAdapter("uid=scaladude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "scaladude");
Collection<GrantedAuthority> authorities = this.populator.getGrantedAuthorities(ctx, "scaladude");
assertThat(authorities).hasSize(1);
assertThat(authorities).isEqualTo(Arrays.asList(scalaDevelopers));
assertThat(authorities).isEqualTo(Arrays.asList(this.scalaDevelopers));
}
@Test
public void testGroovyDudeJDevelopersAuthorities() {
DirContextAdapter ctx = new DirContextAdapter("uid=groovydude,ou=people,dc=springframework,dc=org");
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "groovydude");
Collection<GrantedAuthority> authorities = this.populator.getGrantedAuthorities(ctx, "groovydude");
assertThat(authorities).hasSize(4);
assertThat(authorities)
.isEqualTo(Arrays.asList(javaDevelopers, circularJavaDevelopers, groovyDevelopers, jDevelopers));
assertThat(authorities).isEqualTo(Arrays.asList(this.javaDevelopers, this.circularJavaDevelopers,
this.groovyDevelopers, this.jDevelopers));
}
@Test
public void testClosureDudeJDevelopersWithMembershipAsAttributeValues() {
populator.setAttributeNames(new HashSet(Arrays.asList("member")));
this.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");
Collection<GrantedAuthority> authorities = this.populator.getGrantedAuthorities(ctx, "closuredude");
assertThat(authorities).hasSize(5);
assertThat(authorities).isEqualTo(Arrays.asList(javaDevelopers, circularJavaDevelopers, closureDevelopers,
groovyDevelopers, jDevelopers));
assertThat(authorities).isEqualTo(Arrays.asList(this.javaDevelopers, this.circularJavaDevelopers,
this.closureDevelopers, this.groovyDevelopers, this.jDevelopers));
LdapAuthority[] ldapAuthorities = authorities.toArray(new LdapAuthority[0]);
assertThat(ldapAuthorities).hasSize(5);
@@ -137,7 +137,7 @@ public class NestedLdapAuthoritiesPopulatorTests {
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(this.groovyDevelopers.getDn()).isEqualTo(ldapAuthorities[1].getFirstAttributeValue("member"));
assertThat(ldapAuthorities[2].getAttributes().get("member"))
.contains("uid=closuredude,ou=people,dc=springframework,dc=org");
@@ -146,7 +146,7 @@ public class NestedLdapAuthoritiesPopulatorTests {
assertThat(ldapAuthorities[2].getAttributeValues("test")).isNotNull();
assertThat(ldapAuthorities[2].getAttributeValues("test")).isEmpty();
// test role name
assertThat(ldapAuthorities[3].getAuthority()).isEqualTo(groovyDevelopers.getAuthority());
assertThat(ldapAuthorities[3].getAuthority()).isEqualTo(this.groovyDevelopers.getAuthority());
}
}
@@ -44,9 +44,9 @@ public class DefaultLdapUsernameToDnMapper implements LdapUsernameToDnMapper {
* Assembles the Distinguished Name that should be used the given username.
*/
public DistinguishedName buildDn(String username) {
DistinguishedName dn = new DistinguishedName(userDnBase);
DistinguishedName dn = new DistinguishedName(this.userDnBase);
dn.add(usernameAttribute, username);
dn.add(this.usernameAttribute, username);
return dn;
}
@@ -76,7 +76,7 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
Assert.notNull(contextSource, "ContextSource cannot be null");
setContextSource(contextSource);
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
this.searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
}
/**
@@ -211,7 +211,7 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
};
SearchControls ctls = new SearchControls();
ctls.setSearchScope(searchControls.getSearchScope());
ctls.setSearchScope(this.searchControls.getSearchScope());
ctls.setReturningAttributes(attributeNames != null && attributeNames.length > 0 ? attributeNames : null);
search(base, formattedFilter, ctls, roleMapper);
@@ -284,7 +284,7 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
public DirContextOperations searchForSingleEntry(final String base, final String filter, final Object[] params) {
return (DirContextOperations) executeReadOnly(
(ContextExecutor) ctx -> searchForSingleEntryInternal(ctx, searchControls, base, filter, params));
(ContextExecutor) ctx -> searchForSingleEntryInternal(ctx, this.searchControls, base, filter, params));
}
/**
@@ -67,16 +67,16 @@ public abstract class AbstractLdapAuthenticator implements LdapAuthenticator, In
}
public void afterPropertiesSet() {
Assert.isTrue((userDnFormat != null) || (userSearch != null),
Assert.isTrue((this.userDnFormat != null) || (this.userSearch != null),
"Either an LdapUserSearch or DN pattern (or both) must be supplied.");
}
protected ContextSource getContextSource() {
return contextSource;
return this.contextSource;
}
public String[] getUserAttributes() {
return userAttributes;
return this.userAttributes;
}
/**
@@ -87,15 +87,15 @@ public abstract class AbstractLdapAuthenticator implements LdapAuthenticator, In
* set.
*/
protected List<String> getUserDns(String username) {
if (userDnFormat == null) {
if (this.userDnFormat == null) {
return Collections.emptyList();
}
List<String> userDns = new ArrayList<>(userDnFormat.length);
List<String> userDns = new ArrayList<>(this.userDnFormat.length);
String[] args = new String[] { LdapEncoder.nameEncode(username) };
synchronized (userDnFormat) {
for (MessageFormat formatter : userDnFormat) {
synchronized (this.userDnFormat) {
for (MessageFormat formatter : this.userDnFormat) {
userDns.add(formatter.format(args));
}
}
@@ -104,7 +104,7 @@ public abstract class AbstractLdapAuthenticator implements LdapAuthenticator, In
}
protected LdapUserSearch getUserSearch() {
return userSearch;
return this.userSearch;
}
public void setMessageSource(MessageSource messageSource) {
@@ -131,10 +131,10 @@ public abstract class AbstractLdapAuthenticator implements LdapAuthenticator, In
public void setUserDnPatterns(String[] dnPattern) {
Assert.notNull(dnPattern, "The array of DN patterns cannot be set to null");
// this.userDnPattern = dnPattern;
userDnFormat = new MessageFormat[dnPattern.length];
this.userDnFormat = new MessageFormat[dnPattern.length];
for (int i = 0; i < dnPattern.length; i++) {
userDnFormat[i] = new MessageFormat(dnPattern[i]);
this.userDnFormat[i] = new MessageFormat(dnPattern[i]);
}
}
@@ -67,7 +67,8 @@ public class BindAuthenticator extends AbstractLdapAuthenticator {
if (!StringUtils.hasLength(password)) {
logger.debug("Rejecting empty password for user " + username);
throw new BadCredentialsException(messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password"));
throw new BadCredentialsException(
this.messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password"));
}
// If DN patterns are configured, try authenticating with them directly
@@ -88,7 +89,7 @@ public class BindAuthenticator extends AbstractLdapAuthenticator {
if (user == null) {
throw new BadCredentialsException(
messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
this.messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
}
return user;
@@ -92,23 +92,23 @@ public final class PasswordComparisonAuthenticator extends AbstractLdapAuthentic
}
if (logger.isDebugEnabled()) {
logger.debug("Performing LDAP compare of password attribute '" + passwordAttributeName + "' for user '"
logger.debug("Performing LDAP compare of password attribute '" + this.passwordAttributeName + "' for user '"
+ user.getDn() + "'");
}
if (usePasswordAttrCompare && isPasswordAttrCompare(user, password)) {
if (this.usePasswordAttrCompare && isPasswordAttrCompare(user, password)) {
return user;
}
else if (isLdapPasswordCompare(user, ldapTemplate, password)) {
return user;
}
throw new BadCredentialsException(
messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
this.messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
}
private boolean isPasswordAttrCompare(DirContextOperations user, String password) {
String passwordAttrValue = getPassword(user);
return passwordEncoder.matches(password, passwordAttrValue);
return this.passwordEncoder.matches(password, passwordAttrValue);
}
private String getPassword(DirContextOperations user) {
@@ -124,9 +124,9 @@ public final class PasswordComparisonAuthenticator extends AbstractLdapAuthentic
private boolean isLdapPasswordCompare(DirContextOperations user, SpringSecurityLdapTemplate ldapTemplate,
String password) {
String encodedPassword = passwordEncoder.encode(password);
String encodedPassword = this.passwordEncoder.encode(password);
byte[] passwordBytes = Utf8.encode(encodedPassword);
return ldapTemplate.compare(user.getDn().toString(), passwordAttributeName, passwordBytes);
return ldapTemplate.compare(user.getDn().toString(), this.passwordAttributeName, passwordBytes);
}
public void setPasswordAttributeName(String passwordAttribute) {
@@ -41,7 +41,7 @@ public class UserDetailsServiceLdapAuthoritiesPopulator implements LdapAuthoriti
public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData,
String username) {
return userDetailsService.loadUserByUsername(username).getAuthorities();
return this.userDetailsService.loadUserByUsername(username).getAuthorities();
}
}
@@ -50,7 +50,7 @@ public final class ActiveDirectoryAuthenticationException extends Authentication
}
public String getDataCode() {
return dataCode;
return this.dataCode;
}
}
@@ -152,7 +152,7 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
Assert.isTrue(StringUtils.hasText(url), "Url cannot be empty");
this.domain = StringUtils.hasText(domain) ? domain.toLowerCase() : null;
this.url = url;
rootDn = this.domain == null ? null : rootDnFromDomain(this.domain);
this.rootDn = this.domain == null ? null : rootDnFromDomain(this.domain);
}
@Override
@@ -169,7 +169,7 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
throw badLdapConnection(e);
}
catch (NamingException e) {
logger.error("Failed to locate directory entry for authenticated user: " + username, e);
this.logger.error("Failed to locate directory entry for authenticated user: " + username, e);
throw badCredentials(e);
}
finally {
@@ -187,13 +187,13 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
String[] groups = userData.getStringAttributes("memberOf");
if (groups == null) {
logger.debug("No values for 'memberOf' attribute.");
this.logger.debug("No values for 'memberOf' attribute.");
return AuthorityUtils.NO_AUTHORITIES;
}
if (logger.isDebugEnabled()) {
logger.debug("'memberOf' attribute values: " + Arrays.asList(groups));
if (this.logger.isDebugEnabled()) {
this.logger.debug("'memberOf' attribute values: " + Arrays.asList(groups));
}
ArrayList<GrantedAuthority> authorities = new ArrayList<>(groups.length);
@@ -207,7 +207,7 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
private DirContext bindAsUser(String username, String password) {
// TODO. add DNS lookup based on domain
final String bindUrl = url;
final String bindUrl = this.url;
Hashtable<String, Object> env = new Hashtable<>();
env.put(Context.SECURITY_AUTHENTICATION, "simple");
@@ -220,7 +220,7 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
env.putAll(this.contextEnvironmentProperties);
try {
return contextFactory.createContext(env);
return this.contextFactory.createContext(env);
}
catch (NamingException e) {
if ((e instanceof AuthenticationException) || (e instanceof OperationNotSupportedException)) {
@@ -234,8 +234,8 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
}
private void handleBindException(String bindPrincipal, NamingException exception) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication for " + bindPrincipal + " failed:" + exception);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Authentication for " + bindPrincipal + " failed:" + exception);
}
handleResolveObj(exception);
@@ -243,13 +243,13 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
int subErrorCode = parseSubErrorCode(exception.getMessage());
if (subErrorCode <= 0) {
logger.debug("Failed to locate AD-specific sub-error code in message");
this.logger.debug("Failed to locate AD-specific sub-error code in message");
return;
}
logger.info("Active Directory authentication failed: " + subCodeToLogMessage(subErrorCode));
this.logger.info("Active Directory authentication failed: " + subCodeToLogMessage(subErrorCode));
if (convertSubErrorCodesToExceptions) {
if (this.convertSubErrorCodesToExceptions) {
raiseExceptionForErrorCode(subErrorCode, exception);
}
}
@@ -277,17 +277,17 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
Throwable cause = new ActiveDirectoryAuthenticationException(hexString, exception.getMessage(), exception);
switch (code) {
case PASSWORD_EXPIRED:
throw new CredentialsExpiredException(messages.getMessage("LdapAuthenticationProvider.credentialsExpired",
"User credentials have expired"), cause);
throw new CredentialsExpiredException(this.messages.getMessage(
"LdapAuthenticationProvider.credentialsExpired", "User credentials have expired"), cause);
case ACCOUNT_DISABLED:
throw new DisabledException(messages.getMessage("LdapAuthenticationProvider.disabled", "User is disabled"),
cause);
throw new DisabledException(
this.messages.getMessage("LdapAuthenticationProvider.disabled", "User is disabled"), cause);
case ACCOUNT_EXPIRED:
throw new AccountExpiredException(
messages.getMessage("LdapAuthenticationProvider.expired", "User account has expired"), cause);
this.messages.getMessage("LdapAuthenticationProvider.expired", "User account has expired"), cause);
case ACCOUNT_LOCKED:
throw new LockedException(
messages.getMessage("LdapAuthenticationProvider.locked", "User account is locked"), cause);
this.messages.getMessage("LdapAuthenticationProvider.locked", "User account is locked"), cause);
default:
throw badCredentials(cause);
}
@@ -318,7 +318,7 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
private BadCredentialsException badCredentials() {
return new BadCredentialsException(
messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
this.messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
}
private BadCredentialsException badCredentials(Throwable cause) {
@@ -326,7 +326,7 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
}
private InternalAuthenticationServiceException badLdapConnection(Throwable cause) {
return new InternalAuthenticationServiceException(messages.getMessage(
return new InternalAuthenticationServiceException(this.messages.getMessage(
"LdapAuthenticationProvider.badLdapConnection", "Connection to LDAP server failed."), cause);
}
@@ -335,11 +335,11 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String bindPrincipal = createBindPrincipal(username);
String searchRoot = rootDn != null ? rootDn : searchRootFromPrincipal(bindPrincipal);
String searchRoot = this.rootDn != null ? this.rootDn : searchRootFromPrincipal(bindPrincipal);
try {
return SpringSecurityLdapTemplate.searchForSingleEntryInternal(context, searchControls, searchRoot,
searchFilter, new Object[] { bindPrincipal, username });
this.searchFilter, new Object[] { bindPrincipal, username });
}
catch (CommunicationException ldapCommunicationException) {
throw badLdapConnection(ldapCommunicationException);
@@ -361,7 +361,7 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
int atChar = bindPrincipal.lastIndexOf('@');
if (atChar < 0) {
logger.debug("User principal '" + bindPrincipal
this.logger.debug("User principal '" + bindPrincipal
+ "' does not contain the domain, and no domain has been configured");
throw badCredentials();
}
@@ -384,11 +384,11 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda
}
String createBindPrincipal(String username) {
if (domain == null || username.toLowerCase().endsWith(domain)) {
if (this.domain == null || username.toLowerCase().endsWith(this.domain)) {
return username;
}
return username + "@" + domain;
return username + "@" + this.domain;
}
/**
@@ -45,18 +45,18 @@ public class PasswordPolicyAwareContextSource extends DefaultSpringSecurityConte
@Override
public DirContext getContext(String principal, String credentials) throws PasswordPolicyException {
if (principal.equals(userDn)) {
if (principal.equals(this.userDn)) {
return super.getContext(principal, credentials);
}
final boolean debug = logger.isDebugEnabled();
final boolean debug = this.logger.isDebugEnabled();
if (debug) {
logger.debug("Binding as '" + userDn + "', prior to reconnect as user '" + principal + "'");
this.logger.debug("Binding as '" + this.userDn + "', prior to reconnect as user '" + principal + "'");
}
// First bind as manager user before rebinding as the specific principal.
LdapContext ctx = (LdapContext) super.getContext(userDn, password);
LdapContext ctx = (LdapContext) super.getContext(this.userDn, this.password);
Control[] rctls = { new PasswordPolicyControl(false) };
@@ -68,8 +68,8 @@ public class PasswordPolicyAwareContextSource extends DefaultSpringSecurityConte
catch (javax.naming.NamingException ne) {
PasswordPolicyResponseControl ctrl = PasswordPolicyControlExtractor.extractControl(ctx);
if (debug) {
logger.debug("Failed to obtain context", ne);
logger.debug("Password policy response: " + ctrl);
this.logger.debug("Failed to obtain context", ne);
this.logger.debug("Password policy response: " + ctrl);
}
LdapUtils.closeContext(ctx);
@@ -84,7 +84,7 @@ public class PasswordPolicyAwareContextSource extends DefaultSpringSecurityConte
}
if (debug) {
logger.debug("PPolicy control returned: " + PasswordPolicyControlExtractor.extractControl(ctx));
this.logger.debug("PPolicy control returned: " + PasswordPolicyControlExtractor.extractControl(ctx));
}
return ctx;
@@ -72,7 +72,7 @@ public class PasswordPolicyControl implements Control {
* Returns whether the control is critical for the client.
*/
public boolean isCritical() {
return critical;
return this.critical;
}
}
@@ -65,11 +65,11 @@ public enum PasswordPolicyErrorStatus {
}
public String getErrorCode() {
return errorCode;
return this.errorCode;
}
public String getDefaultMessage() {
return defaultMessage;
return this.defaultMessage;
}
}
@@ -34,7 +34,7 @@ public class PasswordPolicyException extends RuntimeException {
}
public PasswordPolicyErrorStatus getStatus() {
return status;
return this.status;
}
}
@@ -99,13 +99,13 @@ public class FilterBasedLdapUserSearch implements LdapUserSearch {
logger.debug("Searching for user '" + username + "', with user search " + this);
}
SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(contextSource);
SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(this.contextSource);
template.setSearchControls(searchControls);
template.setSearchControls(this.searchControls);
try {
return template.searchForSingleEntry(searchBase, searchFilter, new String[] { username });
return template.searchForSingleEntry(this.searchBase, this.searchFilter, new String[] { username });
}
catch (IncorrectResultSizeDataAccessException notFound) {
@@ -124,7 +124,7 @@ public class FilterBasedLdapUserSearch implements LdapUserSearch {
* @param deref the derefLinkFlag value as defined in SearchControls..
*/
public void setDerefLinkFlag(boolean deref) {
searchControls.setDerefLinkFlag(deref);
this.searchControls.setDerefLinkFlag(deref);
}
/**
@@ -134,7 +134,8 @@ public class FilterBasedLdapUserSearch implements LdapUserSearch {
* SearchControls.SUBTREE_SCOPE rather than SearchControls.ONELEVEL_SCOPE.
*/
public void setSearchSubtree(boolean searchSubtree) {
searchControls.setSearchScope(searchSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
this.searchControls
.setSearchScope(searchSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
}
/**
@@ -142,7 +143,7 @@ public class FilterBasedLdapUserSearch implements LdapUserSearch {
* @param searchTimeLimit the time limit for the search (in milliseconds).
*/
public void setSearchTimeLimit(int searchTimeLimit) {
searchControls.setTimeLimit(searchTimeLimit);
this.searchControls.setTimeLimit(searchTimeLimit);
}
/**
@@ -154,19 +155,19 @@ public class FilterBasedLdapUserSearch implements LdapUserSearch {
* returned. Can be null.
*/
public void setReturningAttributes(String[] attrs) {
searchControls.setReturningAttributes(attrs);
this.searchControls.setReturningAttributes(attrs);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[ searchFilter: '").append(searchFilter).append("', ");
sb.append("searchBase: '").append(searchBase).append("'");
sb.append(", scope: ")
.append(searchControls.getSearchScope() == SearchControls.SUBTREE_SCOPE ? "subtree" : "single-level, ");
sb.append(", searchTimeLimit: ").append(searchControls.getTimeLimit());
sb.append(", derefLinkFlag: ").append(searchControls.getDerefLinkFlag()).append(" ]");
sb.append("[ searchFilter: '").append(this.searchFilter).append("', ");
sb.append("searchBase: '").append(this.searchBase).append("'");
sb.append(", scope: ").append(
this.searchControls.getSearchScope() == SearchControls.SUBTREE_SCOPE ? "subtree" : "single-level, ");
sb.append(", searchTimeLimit: ").append(this.searchControls.getTimeLimit());
sb.append(", derefLinkFlag: ").append(this.searchControls.getDerefLinkFlag()).append(" ]");
return sb.toString();
}
@@ -110,7 +110,7 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
public ApacheDSContainer(String root, String ldifs) throws Exception {
this.ldifResources = ldifs;
service = new DefaultDirectoryService();
this.service = new DefaultDirectoryService();
List<Interceptor> list = new ArrayList<>();
list.add(new NormalizationInterceptor());
@@ -128,20 +128,20 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
// list.add( new TriggerInterceptor() );
// list.add( new JournalInterceptor() );
service.setInterceptors(list);
partition = new JdbmPartition();
partition.setId("rootPartition");
partition.setSuffix(root);
this.service.setInterceptors(list);
this.partition = new JdbmPartition();
this.partition.setId("rootPartition");
this.partition.setSuffix(root);
this.root = root;
service.addPartition(partition);
service.setExitVmOnShutdown(false);
service.setShutdownHookEnabled(false);
service.getChangeLog().setEnabled(false);
service.setDenormalizeOpAttrsEnabled(true);
this.service.addPartition(this.partition);
this.service.setExitVmOnShutdown(false);
this.service.setShutdownHookEnabled(false);
this.service.getChangeLog().setEnabled(false);
this.service.setDenormalizeOpAttrsEnabled(true);
}
public void afterPropertiesSet() throws Exception {
if (workingDir == null) {
if (this.workingDir == null) {
String apacheWorkDir = System.getProperty("apacheDSWorkDir");
if (apacheWorkDir == null) {
@@ -154,17 +154,17 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
throw new IllegalArgumentException("When LdapOverSsl is enabled, the keyStoreFile property must be set.");
}
server = new LdapServer();
server.setDirectoryService(service);
this.server = new LdapServer();
this.server.setDirectoryService(this.service);
// AbstractLdapIntegrationTests assume IPv4, so we specify the same here
this.transport = new TcpTransport(port);
if (ldapOverSslEnabled) {
transport.setEnableSSL(true);
server.setKeystoreFile(this.keyStoreFile.getAbsolutePath());
server.setCertificatePassword(this.certificatePassord);
this.transport = new TcpTransport(this.port);
if (this.ldapOverSslEnabled) {
this.transport.setEnableSSL(true);
this.server.setKeystoreFile(this.keyStoreFile.getAbsolutePath());
this.server.setCertificatePassword(this.certificatePassord);
}
server.setTransports(transport);
this.server.setTransports(this.transport);
start();
}
@@ -173,13 +173,13 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ctxt = applicationContext;
this.ctxt = applicationContext;
}
public void setWorkingDirectory(File workingDir) {
Assert.notNull(workingDir, "workingDir cannot be null");
logger.info("Setting working directory for LDAP_PROVIDER: " + workingDir.getAbsolutePath());
this.logger.info("Setting working directory for LDAP_PROVIDER: " + workingDir.getAbsolutePath());
if (workingDir.exists()) {
throw new IllegalArgumentException("The specified working directory '" + workingDir.getAbsolutePath()
@@ -190,7 +190,7 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
this.workingDir = workingDir;
service.setWorkingDirectory(workingDir);
this.service.setWorkingDirectory(workingDir);
}
public void setPort(int port) {
@@ -238,7 +238,7 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
}
public DefaultDirectoryService getService() {
return service;
return this.service;
}
public void start() {
@@ -246,45 +246,45 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
return;
}
if (service.isStarted()) {
if (this.service.isStarted()) {
throw new IllegalStateException("DirectoryService is already running.");
}
logger.info("Starting directory server...");
this.logger.info("Starting directory server...");
try {
service.startup();
server.start();
this.service.startup();
this.server.start();
}
catch (Exception e) {
throw new RuntimeException("Server startup failed", e);
}
try {
service.getAdminSession().lookup(partition.getSuffixDn());
this.service.getAdminSession().lookup(this.partition.getSuffixDn());
}
catch (LdapNameNotFoundException e) {
try {
LdapDN dn = new LdapDN(root);
Assert.isTrue(root.startsWith("dc="), "root must start with dc=");
String dc = root.substring(3, root.indexOf(','));
ServerEntry entry = service.newEntry(dn);
LdapDN dn = new LdapDN(this.root);
Assert.isTrue(this.root.startsWith("dc="), "root must start with dc=");
String dc = this.root.substring(3, this.root.indexOf(','));
ServerEntry entry = this.service.newEntry(dn);
entry.add("objectClass", "top", "domain", "extensibleObject");
entry.add("dc", dc);
service.getAdminSession().add(entry);
this.service.getAdminSession().add(entry);
}
catch (Exception e1) {
logger.error("Failed to create dc entry", e1);
this.logger.error("Failed to create dc entry", e1);
}
}
catch (Exception e) {
logger.error("Lookup failed", e);
this.logger.error("Lookup failed", e);
}
SocketAcceptor socketAcceptor = this.server.getSocketAcceptor(this.transport);
InetSocketAddress localAddress = socketAcceptor.getLocalAddress();
this.localPort = localAddress.getPort();
running = true;
this.running = true;
try {
importLdifs();
@@ -299,21 +299,21 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
return;
}
logger.info("Shutting down directory server ...");
this.logger.info("Shutting down directory server ...");
try {
server.stop();
service.shutdown();
this.server.stop();
this.service.shutdown();
}
catch (Exception e) {
logger.error("Shutdown failed", e);
this.logger.error("Shutdown failed", e);
return;
}
running = false;
this.running = false;
if (workingDir.exists()) {
logger.info("Deleting working directory " + workingDir.getAbsolutePath());
deleteDir(workingDir);
if (this.workingDir.exists()) {
this.logger.info("Deleting working directory " + this.workingDir.getAbsolutePath());
deleteDir(this.workingDir);
}
}
@@ -321,12 +321,12 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
// Import any ldif files
Resource[] ldifs;
if (ctxt == null) {
if (this.ctxt == null) {
// Not running within an app context
ldifs = new PathMatchingResourcePatternResolver().getResources(ldifResources);
ldifs = new PathMatchingResourcePatternResolver().getResources(this.ldifResources);
}
else {
ldifs = ctxt.getResources(ldifResources);
ldifs = this.ctxt.getResources(this.ldifResources);
}
// Note that we can't just import using the ServerContext returned
@@ -348,14 +348,14 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
catch (IOException e) {
ldifFile = ldifs[0].getURI().toString();
}
logger.info("Loading LDIF file: " + ldifFile);
LdifFileLoader loader = new LdifFileLoader(service.getAdminSession(), new File(ldifFile), null,
this.logger.info("Loading LDIF file: " + ldifFile);
LdifFileLoader loader = new LdifFileLoader(this.service.getAdminSession(), new File(ldifFile), null,
getClass().getClassLoader());
loader.execute();
}
else {
throw new IllegalArgumentException("More than one LDIF resource found with the supplied pattern:"
+ ldifResources + " Got " + Arrays.toString(ldifs));
+ this.ldifResources + " Got " + Arrays.toString(ldifs));
}
}
@@ -391,7 +391,7 @@ public class ApacheDSContainer implements InitializingBean, DisposableBean, Life
}
public boolean isRunning() {
return running;
return this.running;
}
}
@@ -246,7 +246,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
}
for (Map<String, List<String>> role : userRoles) {
authorities.add(authorityMapper.apply(role));
authorities.add(this.authorityMapper.apply(role));
}
return authorities;
@@ -73,96 +73,96 @@ public class InetOrgPerson extends Person {
private String uid;
public String getUid() {
return uid;
return this.uid;
}
public String getMail() {
return mail;
return this.mail;
}
public String getEmployeeNumber() {
return employeeNumber;
return this.employeeNumber;
}
public String getInitials() {
return initials;
return this.initials;
}
public String getDestinationIndicator() {
return destinationIndicator;
return this.destinationIndicator;
}
public String getO() {
return o;
return this.o;
}
public String getOu() {
return ou;
return this.ou;
}
public String getTitle() {
return title;
return this.title;
}
public String getCarLicense() {
return carLicense;
return this.carLicense;
}
public String getDepartmentNumber() {
return departmentNumber;
return this.departmentNumber;
}
public String getDisplayName() {
return displayName;
return this.displayName;
}
public String getHomePhone() {
return homePhone;
return this.homePhone;
}
public String getRoomNumber() {
return roomNumber;
return this.roomNumber;
}
public String getHomePostalAddress() {
return homePostalAddress;
return this.homePostalAddress;
}
public String getMobile() {
return mobile;
return this.mobile;
}
public String getPostalAddress() {
return postalAddress;
return this.postalAddress;
}
public String getPostalCode() {
return postalCode;
return this.postalCode;
}
public String getStreet() {
return street;
return this.street;
}
protected void populateContext(DirContextAdapter adapter) {
super.populateContext(adapter);
adapter.setAttributeValue("carLicense", carLicense);
adapter.setAttributeValue("departmentNumber", departmentNumber);
adapter.setAttributeValue("destinationIndicator", destinationIndicator);
adapter.setAttributeValue("displayName", displayName);
adapter.setAttributeValue("employeeNumber", employeeNumber);
adapter.setAttributeValue("homePhone", homePhone);
adapter.setAttributeValue("homePostalAddress", homePostalAddress);
adapter.setAttributeValue("initials", initials);
adapter.setAttributeValue("mail", mail);
adapter.setAttributeValue("mobile", mobile);
adapter.setAttributeValue("postalAddress", postalAddress);
adapter.setAttributeValue("postalCode", postalCode);
adapter.setAttributeValue("ou", ou);
adapter.setAttributeValue("o", o);
adapter.setAttributeValue("roomNumber", roomNumber);
adapter.setAttributeValue("street", street);
adapter.setAttributeValue("uid", uid);
adapter.setAttributeValue("carLicense", this.carLicense);
adapter.setAttributeValue("departmentNumber", this.departmentNumber);
adapter.setAttributeValue("destinationIndicator", this.destinationIndicator);
adapter.setAttributeValue("displayName", this.displayName);
adapter.setAttributeValue("employeeNumber", this.employeeNumber);
adapter.setAttributeValue("homePhone", this.homePhone);
adapter.setAttributeValue("homePostalAddress", this.homePostalAddress);
adapter.setAttributeValue("initials", this.initials);
adapter.setAttributeValue("mail", this.mail);
adapter.setAttributeValue("mobile", this.mobile);
adapter.setAttributeValue("postalAddress", this.postalAddress);
adapter.setAttributeValue("postalCode", this.postalCode);
adapter.setAttributeValue("ou", this.ou);
adapter.setAttributeValue("o", this.o);
adapter.setAttributeValue("roomNumber", this.roomNumber);
adapter.setAttributeValue("street", this.street);
adapter.setAttributeValue("uid", this.uid);
adapter.setAttributeValues("objectclass",
new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" });
}
@@ -221,79 +221,79 @@ public class InetOrgPerson extends Person {
}
public void setMail(String email) {
((InetOrgPerson) instance).mail = email;
((InetOrgPerson) this.instance).mail = email;
}
public void setUid(String uid) {
((InetOrgPerson) instance).uid = uid;
((InetOrgPerson) this.instance).uid = uid;
if (instance.getUsername() == null) {
if (this.instance.getUsername() == null) {
setUsername(uid);
}
}
public void setInitials(String initials) {
((InetOrgPerson) instance).initials = initials;
((InetOrgPerson) this.instance).initials = initials;
}
public void setO(String organization) {
((InetOrgPerson) instance).o = organization;
((InetOrgPerson) this.instance).o = organization;
}
public void setOu(String ou) {
((InetOrgPerson) instance).ou = ou;
((InetOrgPerson) this.instance).ou = ou;
}
public void setRoomNumber(String no) {
((InetOrgPerson) instance).roomNumber = no;
((InetOrgPerson) this.instance).roomNumber = no;
}
public void setTitle(String title) {
((InetOrgPerson) instance).title = title;
((InetOrgPerson) this.instance).title = title;
}
public void setCarLicense(String carLicense) {
((InetOrgPerson) instance).carLicense = carLicense;
((InetOrgPerson) this.instance).carLicense = carLicense;
}
public void setDepartmentNumber(String departmentNumber) {
((InetOrgPerson) instance).departmentNumber = departmentNumber;
((InetOrgPerson) this.instance).departmentNumber = departmentNumber;
}
public void setDisplayName(String displayName) {
((InetOrgPerson) instance).displayName = displayName;
((InetOrgPerson) this.instance).displayName = displayName;
}
public void setEmployeeNumber(String no) {
((InetOrgPerson) instance).employeeNumber = no;
((InetOrgPerson) this.instance).employeeNumber = no;
}
public void setDestinationIndicator(String destination) {
((InetOrgPerson) instance).destinationIndicator = destination;
((InetOrgPerson) this.instance).destinationIndicator = destination;
}
public void setHomePhone(String homePhone) {
((InetOrgPerson) instance).homePhone = homePhone;
((InetOrgPerson) this.instance).homePhone = homePhone;
}
public void setStreet(String street) {
((InetOrgPerson) instance).street = street;
((InetOrgPerson) this.instance).street = street;
}
public void setPostalCode(String postalCode) {
((InetOrgPerson) instance).postalCode = postalCode;
((InetOrgPerson) this.instance).postalCode = postalCode;
}
public void setPostalAddress(String postalAddress) {
((InetOrgPerson) instance).postalAddress = postalAddress;
((InetOrgPerson) this.instance).postalAddress = postalAddress;
}
public void setMobile(String mobile) {
((InetOrgPerson) instance).mobile = mobile;
((InetOrgPerson) this.instance).mobile = mobile;
}
public void setHomePostalAddress(String homePostalAddress) {
((InetOrgPerson) instance).homePostalAddress = homePostalAddress;
((InetOrgPerson) this.instance).homePostalAddress = homePostalAddress;
}
}
@@ -65,7 +65,7 @@ public class LdapAuthority implements GrantedAuthority {
* @return the LDAP attributes, map can be null
*/
public Map<String, List<String>> getAttributes() {
return attributes;
return this.attributes;
}
/**
@@ -73,7 +73,7 @@ public class LdapAuthority implements GrantedAuthority {
* @return
*/
public String getDn() {
return dn;
return this.dn;
}
/**
@@ -83,8 +83,8 @@ public class LdapAuthority implements GrantedAuthority {
*/
public List<String> getAttributeValues(String name) {
List<String> result = null;
if (attributes != null) {
result = attributes.get(name);
if (this.attributes != null) {
result = this.attributes.get(name);
}
if (result == null) {
result = Collections.emptyList();
@@ -112,7 +112,7 @@ public class LdapAuthority implements GrantedAuthority {
*/
@Override
public String getAuthority() {
return role;
return this.role;
}
/**
@@ -130,22 +130,22 @@ public class LdapAuthority implements GrantedAuthority {
LdapAuthority that = (LdapAuthority) o;
if (!dn.equals(that.dn)) {
if (!this.dn.equals(that.dn)) {
return false;
}
return role.equals(that.role);
return this.role.equals(that.role);
}
@Override
public int hashCode() {
int result = dn.hashCode();
result = 31 * result + (role != null ? role.hashCode() : 0);
int result = this.dn.hashCode();
result = 31 * result + (this.role != null ? this.role.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "LdapAuthority{" + "dn='" + dn + '\'' + ", role='" + role + '\'' + '}';
return "LdapAuthority{" + "dn='" + this.dn + '\'' + ", role='" + this.role + '\'' + '}';
}
}
@@ -77,77 +77,77 @@ public class LdapUserDetailsImpl implements LdapUserDetails, PasswordPolicyData
@Override
public Collection<GrantedAuthority> getAuthorities() {
return authorities;
return this.authorities;
}
@Override
public String getDn() {
return dn;
return this.dn;
}
@Override
public String getPassword() {
return password;
return this.password;
}
@Override
public String getUsername() {
return username;
return this.username;
}
@Override
public boolean isAccountNonExpired() {
return accountNonExpired;
return this.accountNonExpired;
}
@Override
public boolean isAccountNonLocked() {
return accountNonLocked;
return this.accountNonLocked;
}
@Override
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
return this.credentialsNonExpired;
}
@Override
public boolean isEnabled() {
return enabled;
return this.enabled;
}
@Override
public void eraseCredentials() {
password = null;
this.password = null;
}
@Override
public int getTimeBeforeExpiration() {
return timeBeforeExpiration;
return this.timeBeforeExpiration;
}
@Override
public int getGraceLoginsRemaining() {
return graceLoginsRemaining;
return this.graceLoginsRemaining;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof LdapUserDetailsImpl) {
return dn.equals(((LdapUserDetailsImpl) obj).dn);
return this.dn.equals(((LdapUserDetailsImpl) obj).dn);
}
return false;
}
@Override
public int hashCode() {
return dn.hashCode();
return this.dn.hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString()).append(": ");
sb.append("Dn: ").append(dn).append("; ");
sb.append("Dn: ").append(this.dn).append("; ");
sb.append("Username: ").append(this.username).append("; ");
sb.append("Password: [PROTECTED]; ");
sb.append("Enabled: ").append(this.enabled).append("; ");
@@ -214,12 +214,12 @@ public class LdapUserDetailsImpl implements LdapUserDetails, PasswordPolicyData
*/
public void addAuthority(GrantedAuthority a) {
if (!hasAuthority(a)) {
mutableAuthorities.add(a);
this.mutableAuthorities.add(a);
}
}
private boolean hasAuthority(GrantedAuthority a) {
for (GrantedAuthority authority : mutableAuthorities) {
for (GrantedAuthority authority : this.mutableAuthorities) {
if (authority.equals(a)) {
return true;
}
@@ -228,66 +228,66 @@ public class LdapUserDetailsImpl implements LdapUserDetails, PasswordPolicyData
}
public LdapUserDetails createUserDetails() {
Assert.notNull(instance, "Essence can only be used to create a single instance");
Assert.notNull(instance.username, "username must not be null");
Assert.notNull(instance.getDn(), "Distinguished name must not be null");
Assert.notNull(this.instance, "Essence can only be used to create a single instance");
Assert.notNull(this.instance.username, "username must not be null");
Assert.notNull(this.instance.getDn(), "Distinguished name must not be null");
instance.authorities = Collections.unmodifiableList(mutableAuthorities);
this.instance.authorities = Collections.unmodifiableList(this.mutableAuthorities);
LdapUserDetails newInstance = instance;
LdapUserDetails newInstance = this.instance;
instance = null;
this.instance = null;
return newInstance;
}
public Collection<GrantedAuthority> getGrantedAuthorities() {
return mutableAuthorities;
return this.mutableAuthorities;
}
public void setAccountNonExpired(boolean accountNonExpired) {
instance.accountNonExpired = accountNonExpired;
this.instance.accountNonExpired = accountNonExpired;
}
public void setAccountNonLocked(boolean accountNonLocked) {
instance.accountNonLocked = accountNonLocked;
this.instance.accountNonLocked = accountNonLocked;
}
public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
mutableAuthorities = new ArrayList<>();
mutableAuthorities.addAll(authorities);
this.mutableAuthorities = new ArrayList<>();
this.mutableAuthorities.addAll(authorities);
}
public void setCredentialsNonExpired(boolean credentialsNonExpired) {
instance.credentialsNonExpired = credentialsNonExpired;
this.instance.credentialsNonExpired = credentialsNonExpired;
}
public void setDn(String dn) {
instance.dn = dn;
this.instance.dn = dn;
}
public void setDn(Name dn) {
instance.dn = dn.toString();
this.instance.dn = dn.toString();
}
public void setEnabled(boolean enabled) {
instance.enabled = enabled;
this.instance.enabled = enabled;
}
public void setPassword(String password) {
instance.password = password;
this.instance.password = password;
}
public void setUsername(String username) {
instance.username = username;
this.instance.username = username;
}
public void setTimeBeforeExpiration(int timeBeforeExpiration) {
instance.timeBeforeExpiration = timeBeforeExpiration;
this.instance.timeBeforeExpiration = timeBeforeExpiration;
}
public void setGraceLoginsRemaining(int graceLoginsRemaining) {
instance.graceLoginsRemaining = graceLoginsRemaining;
this.instance.graceLoginsRemaining = graceLoginsRemaining;
}
}
@@ -114,14 +114,14 @@ public class LdapUserDetailsManager implements UserDetailsManager {
/** Default context mapper used to create a set of roles from a list of attributes */
private AttributesMapper roleMapper = attributes -> {
Attribute roleAttr = attributes.get(groupRoleAttributeName);
Attribute roleAttr = attributes.get(this.groupRoleAttributeName);
NamingEnumeration<?> ne = roleAttr.getAll();
// assert ne.hasMore();
Object group = ne.next();
String role = group.toString();
return new SimpleGrantedAuthority(rolePrefix + role.toUpperCase());
return new SimpleGrantedAuthority(this.rolePrefix + role.toUpperCase());
};
private String[] attributesToRetrieve;
@@ -129,24 +129,24 @@ public class LdapUserDetailsManager implements UserDetailsManager {
private boolean usePasswordModifyExtensionOperation = false;
public LdapUserDetailsManager(ContextSource contextSource) {
template = new LdapTemplate(contextSource);
this.template = new LdapTemplate(contextSource);
}
public UserDetails loadUserByUsername(String username) {
DistinguishedName dn = usernameMapper.buildDn(username);
DistinguishedName dn = this.usernameMapper.buildDn(username);
List<GrantedAuthority> authorities = getUserAuthorities(dn, username);
logger.debug("Loading user '" + username + "' with DN '" + dn + "'");
this.logger.debug("Loading user '" + username + "' with DN '" + dn + "'");
DirContextAdapter userCtx = loadUserAsContext(dn, username);
return userDetailsMapper.mapUserFromContext(userCtx, username, authorities);
return this.userDetailsMapper.mapUserFromContext(userCtx, username, authorities);
}
private DirContextAdapter loadUserAsContext(final DistinguishedName dn, final String username) {
return (DirContextAdapter) template.executeReadOnly((ContextExecutor) ctx -> {
return (DirContextAdapter) this.template.executeReadOnly((ContextExecutor) ctx -> {
try {
Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve);
Attributes attrs = ctx.getAttributes(dn, this.attributesToRetrieve);
return new DirContextAdapter(attrs, LdapUtils.getFullDn(dn, ctx));
}
catch (NameNotFoundException notFound) {
@@ -187,11 +187,11 @@ public class LdapUserDetailsManager implements UserDetailsManager {
String username = authentication.getName();
logger.debug("Changing password for user '" + username);
this.logger.debug("Changing password for user '" + username);
DistinguishedName userDn = usernameMapper.buildDn(username);
DistinguishedName userDn = this.usernameMapper.buildDn(username);
if (usePasswordModifyExtensionOperation) {
if (this.usePasswordModifyExtensionOperation) {
changePasswordUsingExtensionOperation(userDn, oldPassword, newPassword);
}
else {
@@ -210,25 +210,26 @@ public class LdapUserDetailsManager implements UserDetailsManager {
SearchExecutor se = ctx -> {
DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx);
SearchControls ctrls = new SearchControls();
ctrls.setReturningAttributes(new String[] { groupRoleAttributeName });
ctrls.setReturningAttributes(new String[] { this.groupRoleAttributeName });
return ctx.search(groupSearchBase, groupSearchFilter, new String[] { fullDn.toUrl(), username }, ctrls);
return ctx.search(this.groupSearchBase, this.groupSearchFilter, new String[] { fullDn.toUrl(), username },
ctrls);
};
AttributesMapperCallbackHandler roleCollector = new AttributesMapperCallbackHandler(roleMapper);
AttributesMapperCallbackHandler roleCollector = new AttributesMapperCallbackHandler(this.roleMapper);
template.search(se, roleCollector);
this.template.search(se, roleCollector);
return roleCollector.getList();
}
public void createUser(UserDetails user) {
DirContextAdapter ctx = new DirContextAdapter();
copyToContext(user, ctx);
DistinguishedName dn = usernameMapper.buildDn(user.getUsername());
DistinguishedName dn = this.usernameMapper.buildDn(user.getUsername());
logger.debug("Creating new user '" + user.getUsername() + "' with DN '" + dn + "'");
this.logger.debug("Creating new user '" + user.getUsername() + "' with DN '" + dn + "'");
template.bind(dn, ctx, null);
this.template.bind(dn, ctx, null);
// Check for any existing authorities which might be set for this DN and remove
// them
@@ -242,9 +243,9 @@ public class LdapUserDetailsManager implements UserDetailsManager {
}
public void updateUser(UserDetails user) {
DistinguishedName dn = usernameMapper.buildDn(user.getUsername());
DistinguishedName dn = this.usernameMapper.buildDn(user.getUsername());
logger.debug("Updating user '" + user.getUsername() + "' with DN '" + dn + "'");
this.logger.debug("Updating user '" + user.getUsername() + "' with DN '" + dn + "'");
List<GrantedAuthority> authorities = getUserAuthorities(dn, user.getUsername());
@@ -264,7 +265,7 @@ public class LdapUserDetailsManager implements UserDetailsManager {
}
}
template.modifyAttributes(dn, mods.toArray(new ModificationItem[0]));
this.template.modifyAttributes(dn, mods.toArray(new ModificationItem[0]));
// template.rebind(dn, ctx, null);
// Remove the old authorities and replace them with the new one
@@ -273,16 +274,16 @@ public class LdapUserDetailsManager implements UserDetailsManager {
}
public void deleteUser(String username) {
DistinguishedName dn = usernameMapper.buildDn(username);
DistinguishedName dn = this.usernameMapper.buildDn(username);
removeAuthorities(dn, getUserAuthorities(dn, username));
template.unbind(dn);
this.template.unbind(dn);
}
public boolean userExists(String username) {
DistinguishedName dn = usernameMapper.buildDn(username);
DistinguishedName dn = this.usernameMapper.buildDn(username);
try {
Object obj = template.lookup(dn);
Object obj = this.template.lookup(dn);
if (obj instanceof Context) {
LdapUtils.closeContext((Context) obj);
}
@@ -299,14 +300,14 @@ public class LdapUserDetailsManager implements UserDetailsManager {
* @return the DN of the corresponding group, including the groupSearchBase
*/
protected DistinguishedName buildGroupDn(String group) {
DistinguishedName dn = new DistinguishedName(groupSearchBase);
dn.add(groupRoleAttributeName, group.toLowerCase());
DistinguishedName dn = new DistinguishedName(this.groupSearchBase);
dn.add(this.groupRoleAttributeName, group.toLowerCase());
return dn;
}
protected void copyToContext(UserDetails user, DirContextAdapter ctx) {
userDetailsMapper.mapUserToContext(user, ctx);
this.userDetailsMapper.mapUserToContext(user, ctx);
}
protected void addAuthorities(DistinguishedName userDn, Collection<? extends GrantedAuthority> authorities) {
@@ -319,12 +320,12 @@ public class LdapUserDetailsManager implements UserDetailsManager {
private void modifyAuthorities(final DistinguishedName userDn,
final Collection<? extends GrantedAuthority> authorities, final int modType) {
template.executeReadWrite((ContextExecutor) ctx -> {
this.template.executeReadWrite((ContextExecutor) ctx -> {
for (GrantedAuthority authority : authorities) {
String group = convertAuthorityToGroup(authority);
DistinguishedName fullDn = LdapUtils.getFullDn(userDn, ctx);
ModificationItem addGroup = new ModificationItem(modType,
new BasicAttribute(groupMemberAttributeName, fullDn.toUrl()));
new BasicAttribute(this.groupMemberAttributeName, fullDn.toUrl()));
ctx.modifyAttributes(buildGroupDn(group), new ModificationItem[] { addGroup });
}
@@ -335,8 +336,8 @@ public class LdapUserDetailsManager implements UserDetailsManager {
private String convertAuthorityToGroup(GrantedAuthority authority) {
String group = authority.getAuthority();
if (group.startsWith(rolePrefix)) {
group = group.substring(rolePrefix.length());
if (group.startsWith(this.rolePrefix)) {
group = group.substring(this.rolePrefix.length());
}
return group;
@@ -413,14 +414,14 @@ public class LdapUserDetailsManager implements UserDetailsManager {
String newPassword) {
final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem(
DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) };
DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(this.passwordAttributeName, newPassword)) };
if (oldPassword == null) {
template.modifyAttributes(userDn, passwordChange);
this.template.modifyAttributes(userDn, passwordChange);
return;
}
template.executeReadWrite(dirCtx -> {
this.template.executeReadWrite(dirCtx -> {
LdapContext ctx = (LdapContext) dirCtx;
ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool");
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(userDn, ctx).toString());
@@ -443,7 +444,7 @@ public class LdapUserDetailsManager implements UserDetailsManager {
private void changePasswordUsingExtensionOperation(DistinguishedName userDn, String oldPassword,
String newPassword) {
template.executeReadWrite(dirCtx -> {
this.template.executeReadWrite(dirCtx -> {
LdapContext ctx = (LdapContext) dirCtx;
String userIdentity = LdapUtils.getFullDn(userDn, ctx).encode();
@@ -54,10 +54,10 @@ public class LdapUserDetailsService implements UserDetailsService {
}
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
DirContextOperations userData = userSearch.searchForUser(username);
DirContextOperations userData = this.userSearch.searchForUser(username);
return userDetailsMapper.mapUserFromContext(userData, username,
authoritiesPopulator.getGrantedAuthorities(userData, username));
return this.userDetailsMapper.mapUserFromContext(userData, username,
this.authoritiesPopulator.getGrantedAuthorities(userData, username));
}
public void setUserDetailsMapper(UserDetailsContextMapper userDetailsMapper) {
@@ -50,28 +50,28 @@ public class Person extends LdapUserDetailsImpl {
}
public String getGivenName() {
return givenName;
return this.givenName;
}
public String getSn() {
return sn;
return this.sn;
}
public String[] getCn() {
return cn.toArray(new String[0]);
return this.cn.toArray(new String[0]);
}
public String getDescription() {
return description;
return this.description;
}
public String getTelephoneNumber() {
return telephoneNumber;
return this.telephoneNumber;
}
protected void populateContext(DirContextAdapter adapter) {
adapter.setAttributeValue("givenName", givenName);
adapter.setAttributeValue("sn", sn);
adapter.setAttributeValue("givenName", this.givenName);
adapter.setAttributeValue("sn", this.sn);
adapter.setAttributeValues("cn", getCn());
adapter.setAttributeValue("description", getDescription());
adapter.setAttributeValue("telephoneNumber", getTelephoneNumber());
@@ -108,7 +108,7 @@ public class Person extends LdapUserDetailsImpl {
setSn(copyMe.sn);
setDescription(copyMe.getDescription());
setTelephoneNumber(copyMe.getTelephoneNumber());
((Person) instance).cn = new ArrayList<>(copyMe.cn);
((Person) this.instance).cn = new ArrayList<>(copyMe.cn);
}
protected LdapUserDetailsImpl createTarget() {
@@ -116,27 +116,27 @@ public class Person extends LdapUserDetailsImpl {
}
public void setGivenName(String givenName) {
((Person) instance).givenName = givenName;
((Person) this.instance).givenName = givenName;
}
public void setSn(String sn) {
((Person) instance).sn = sn;
((Person) this.instance).sn = sn;
}
public void setCn(String[] cn) {
((Person) instance).cn = Arrays.asList(cn);
((Person) this.instance).cn = Arrays.asList(cn);
}
public void addCn(String value) {
((Person) instance).cn.add(value);
((Person) this.instance).cn.add(value);
}
public void setTelephoneNumber(String tel) {
((Person) instance).telephoneNumber = tel;
((Person) this.instance).telephoneNumber = tel;
}
public void setDescription(String desc) {
((Person) instance).description = desc;
((Person) this.instance).description = desc;
}
public LdapUserDetails createUserDetails() {
@@ -60,15 +60,16 @@ public class SpringSecurityLdapTemplateTests {
Object[] params = new Object[] {};
DirContextAdapter searchResultObject = mock(DirContextAdapter.class);
when(ctx.search(any(DistinguishedName.class), eq(filter), eq(params), searchControls.capture()))
.thenReturn(resultsEnum);
when(resultsEnum.hasMore()).thenReturn(true, false);
when(resultsEnum.next()).thenReturn(searchResult);
when(searchResult.getObject()).thenReturn(searchResultObject);
when(this.ctx.search(any(DistinguishedName.class), eq(filter), eq(params), this.searchControls.capture()))
.thenReturn(this.resultsEnum);
when(this.resultsEnum.hasMore()).thenReturn(true, false);
when(this.resultsEnum.next()).thenReturn(this.searchResult);
when(this.searchResult.getObject()).thenReturn(searchResultObject);
SpringSecurityLdapTemplate.searchForSingleEntryInternal(ctx, mock(SearchControls.class), base, filter, params);
SpringSecurityLdapTemplate.searchForSingleEntryInternal(this.ctx, mock(SearchControls.class), base, filter,
params);
assertThat(searchControls.getValue().getReturningObjFlag()).isTrue();
assertThat(this.searchControls.getValue().getReturningObjFlag()).isTrue();
}
}
@@ -212,7 +212,7 @@ public class LdapAuthenticationProviderTests {
}
String getRequestedUsername() {
return username;
return this.username;
}
}
@@ -34,7 +34,7 @@ public class MockUserSearch implements LdapUserSearch {
}
public DirContextOperations searchForUser(String username) {
return user;
return this.user;
}
}
@@ -79,18 +79,18 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
@Before
public void setUp() {
provider = new ActiveDirectoryLdapAuthenticationProvider("mydomain.eu", "ldap://192.168.1.200/");
this.provider = new ActiveDirectoryLdapAuthenticationProvider("mydomain.eu", "ldap://192.168.1.200/");
}
@Test
public void bindPrincipalIsCreatedCorrectly() {
assertThat(provider.createBindPrincipal("joe")).isEqualTo("joe@mydomain.eu");
assertThat(provider.createBindPrincipal("joe@mydomain.eu")).isEqualTo("joe@mydomain.eu");
assertThat(this.provider.createBindPrincipal("joe")).isEqualTo("joe@mydomain.eu");
assertThat(this.provider.createBindPrincipal("joe@mydomain.eu")).isEqualTo("joe@mydomain.eu");
}
@Test
public void successfulAuthenticationProducesExpectedAuthorities() throws Exception {
checkAuthentication("dc=mydomain,dc=eu", provider);
checkAuthentication("dc=mydomain,dc=eu", this.provider);
}
// SEC-1915
@@ -113,7 +113,7 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
// when
customProvider.setSearchFilter(customSearchFilter);
Authentication result = customProvider.authenticate(joe);
Authentication result = customProvider.authenticate(this.joe);
// then
assertThat(result.isAuthenticated()).isTrue();
@@ -137,7 +137,7 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
customProvider.contextFactory = createContextFactoryReturning(ctx);
// when
Authentication result = customProvider.authenticate(joe);
Authentication result = customProvider.authenticate(this.joe);
// then
assertThat(result.isAuthenticated()).isTrue();
@@ -165,7 +165,7 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
customProvider.contextFactory = createContextFactoryReturning(ctx);
// when
Authentication result = customProvider.authenticate(joe);
Authentication result = customProvider.authenticate(this.joe);
// then
assertThat(captor.getValue()).containsExactly("joe@mydomain.eu", "joe");
@@ -174,17 +174,17 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
@Test(expected = IllegalArgumentException.class)
public void setSearchFilterNull() {
provider.setSearchFilter(null);
this.provider.setSearchFilter(null);
}
@Test(expected = IllegalArgumentException.class)
public void setSearchFilterEmpty() {
provider.setSearchFilter(" ");
this.provider.setSearchFilter(" ");
}
@Test
public void nullDomainIsSupportedIfAuthenticatingWithFullUserPrincipal() throws Exception {
provider = new ActiveDirectoryLdapAuthenticationProvider(null, "ldap://192.168.1.200/");
this.provider = new ActiveDirectoryLdapAuthenticationProvider(null, "ldap://192.168.1.200/");
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
@@ -192,16 +192,16 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
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);
this.provider.contextFactory = createContextFactoryReturning(ctx);
try {
provider.authenticate(joe);
this.provider.authenticate(this.joe);
fail("Expected BadCredentialsException for user with no domain information");
}
catch (BadCredentialsException expected) {
}
provider.authenticate(new UsernamePasswordAuthenticationToken("joe@mydomain.eu", "password"));
this.provider.authenticate(new UsernamePasswordAuthenticationToken("joe@mydomain.eu", "password"));
}
@Test(expected = BadCredentialsException.class)
@@ -211,9 +211,9 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
when(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.thenThrow(new NameNotFoundException());
provider.contextFactory = createContextFactoryReturning(ctx);
this.provider.contextFactory = createContextFactoryReturning(ctx);
provider.authenticate(joe);
this.provider.authenticate(this.joe);
}
// SEC-2017
@@ -224,15 +224,15 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
when(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.thenReturn(new EmptyEnumeration<>());
provider.contextFactory = createContextFactoryReturning(ctx);
this.provider.contextFactory = createContextFactoryReturning(ctx);
provider.authenticate(joe);
this.provider.authenticate(this.joe);
}
// SEC-2500
@Test(expected = BadCredentialsException.class)
public void sec2500PreventAnonymousBind() {
provider.authenticate(new UsernamePasswordAuthenticationToken("rwinch", ""));
this.provider.authenticate(new UsernamePasswordAuthenticationToken("rwinch", ""));
}
@SuppressWarnings("unchecked")
@@ -248,42 +248,43 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
when(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.thenReturn(searchResults);
provider.contextFactory = createContextFactoryReturning(ctx);
this.provider.contextFactory = createContextFactoryReturning(ctx);
provider.authenticate(joe);
this.provider.authenticate(this.joe);
}
static final String msg = "[LDAP: error code 49 - 80858585: LdapErr: DSID-DECAFF0, comment: AcceptSecurityContext error, data ";
@Test(expected = BadCredentialsException.class)
public void userNotFoundIsCorrectlyMapped() {
provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "525, xxxx]"));
provider.setConvertSubErrorCodesToExceptions(true);
provider.authenticate(joe);
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "525, xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
}
@Test(expected = BadCredentialsException.class)
public void incorrectPasswordIsCorrectlyMapped() {
provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "52e, xxxx]"));
provider.setConvertSubErrorCodesToExceptions(true);
provider.authenticate(joe);
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "52e, xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
}
@Test(expected = BadCredentialsException.class)
public void notPermittedIsCorrectlyMapped() {
provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "530, xxxx]"));
provider.setConvertSubErrorCodesToExceptions(true);
provider.authenticate(joe);
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "530, xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
}
@Test
public void passwordNeedsResetIsCorrectlyMapped() {
final String dataCode = "773";
provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + dataCode + ", xxxx]"));
provider.setConvertSubErrorCodesToExceptions(true);
this.provider.contextFactory = createContextFactoryThrowing(
new AuthenticationException(msg + dataCode + ", xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
thrown.expect(BadCredentialsException.class);
thrown.expect(new BaseMatcher<BadCredentialsException>() {
this.thrown.expect(BadCredentialsException.class);
this.thrown.expect(new BaseMatcher<BadCredentialsException>() {
private Matcher<Object> causeInstance = CoreMatchers
.instanceOf(ActiveDirectoryAuthenticationException.class);
@@ -292,75 +293,75 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
public boolean matches(Object that) {
Throwable t = (Throwable) that;
ActiveDirectoryAuthenticationException cause = (ActiveDirectoryAuthenticationException) t.getCause();
return causeInstance.matches(cause) && causeDataCode.matches(cause.getDataCode());
return this.causeInstance.matches(cause) && this.causeDataCode.matches(cause.getDataCode());
}
public void describeTo(Description desc) {
desc.appendText("getCause() ");
causeInstance.describeTo(desc);
this.causeInstance.describeTo(desc);
desc.appendText("getCause().getDataCode() ");
causeDataCode.describeTo(desc);
this.causeDataCode.describeTo(desc);
}
});
provider.authenticate(joe);
this.provider.authenticate(this.joe);
}
@Test(expected = CredentialsExpiredException.class)
public void expiredPasswordIsCorrectlyMapped() {
provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "532, xxxx]"));
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "532, xxxx]"));
try {
provider.authenticate(joe);
this.provider.authenticate(this.joe);
fail("BadCredentialsException should had been thrown");
}
catch (BadCredentialsException expected) {
}
provider.setConvertSubErrorCodesToExceptions(true);
provider.authenticate(joe);
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
}
@Test(expected = DisabledException.class)
public void accountDisabledIsCorrectlyMapped() {
provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "533, xxxx]"));
provider.setConvertSubErrorCodesToExceptions(true);
provider.authenticate(joe);
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "533, xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
}
@Test(expected = AccountExpiredException.class)
public void accountExpiredIsCorrectlyMapped() {
provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "701, xxxx]"));
provider.setConvertSubErrorCodesToExceptions(true);
provider.authenticate(joe);
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "701, xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
}
@Test(expected = LockedException.class)
public void accountLockedIsCorrectlyMapped() {
provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "775, xxxx]"));
provider.setConvertSubErrorCodesToExceptions(true);
provider.authenticate(joe);
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "775, xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
}
@Test(expected = BadCredentialsException.class)
public void unknownErrorCodeIsCorrectlyMapped() {
provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "999, xxxx]"));
provider.setConvertSubErrorCodesToExceptions(true);
provider.authenticate(joe);
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "999, xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
}
@Test(expected = BadCredentialsException.class)
public void errorWithNoSubcodeIsHandledCleanly() {
provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg));
provider.setConvertSubErrorCodesToExceptions(true);
provider.authenticate(joe);
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
}
@Test(expected = org.springframework.ldap.CommunicationException.class)
public void nonAuthenticationExceptionIsConvertedToSpringLdapException() throws Throwable {
try {
provider.contextFactory = createContextFactoryThrowing(new CommunicationException(msg));
provider.authenticate(joe);
this.provider.contextFactory = createContextFactoryThrowing(new CommunicationException(msg));
this.provider.authenticate(this.joe);
}
catch (InternalAuthenticationServiceException e) {
// Since GH-8418 ldap communication exception is wrapped into
@@ -376,7 +377,7 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
"mydomain.eu", NON_EXISTING_LDAP_PROVIDER, "dc=ad,dc=eu,dc=mydomain");
noneReachableProvider
.setContextEnvironmentProperties(Collections.singletonMap("com.sun.jndi.ldap.connect.timeout", "5"));
noneReachableProvider.doAuthentication(joe);
noneReachableProvider.doAuthentication(this.joe);
}
@Test
@@ -389,12 +390,12 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
@Test(expected = IllegalArgumentException.class)
public void setContextEnvironmentPropertiesNull() {
provider.setContextEnvironmentProperties(null);
this.provider.setContextEnvironmentProperties(null);
}
@Test(expected = IllegalArgumentException.class)
public void setContextEnvironmentPropertiesEmpty() {
provider.setContextEnvironmentProperties(new Hashtable<>());
this.provider.setContextEnvironmentProperties(new Hashtable<>());
}
@Test
@@ -402,10 +403,10 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
Hashtable<String, Object> env = new Hashtable<>();
env.put("java.naming.ldap.factory.socket", "unknown.package.NonExistingSocketFactory");
provider.setContextEnvironmentProperties(env);
this.provider.setContextEnvironmentProperties(env);
try {
provider.authenticate(joe);
this.provider.authenticate(this.joe);
fail("CommunicationException was expected with a root cause of ClassNotFoundException");
}
catch (InternalAuthenticationServiceException expected) {
@@ -448,13 +449,13 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
provider.contextFactory = createContextFactoryReturning(ctx);
Authentication result = provider.authenticate(joe);
Authentication result = provider.authenticate(this.joe);
assertThat(result.getAuthorities()).isEmpty();
dca.addAttributeValue("memberOf", "CN=Admin,CN=Users,DC=mydomain,DC=eu");
result = provider.authenticate(joe);
result = provider.authenticate(this.joe);
assertThat(result.getAuthorities()).hasSize(1);
}
@@ -468,13 +469,13 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
}
public SearchResult next() {
SearchResult result = sr;
sr = null;
SearchResult result = this.sr;
this.sr = null;
return result;
}
public boolean hasMore() {
return sr != null;
return this.sr != null;
}
public void close() {
@@ -46,42 +46,42 @@ public class PasswordPolicyAwareContextSourceTests {
@Before
public void setUp() {
reset(ctx);
ctxSource = new PasswordPolicyAwareContextSource("ldap://blah:789/dc=springframework,dc=org") {
reset(this.ctx);
this.ctxSource = new PasswordPolicyAwareContextSource("ldap://blah:789/dc=springframework,dc=org") {
@Override
protected DirContext createContext(Hashtable env) {
if ("manager".equals(env.get(Context.SECURITY_PRINCIPAL))) {
return ctx;
return PasswordPolicyAwareContextSourceTests.this.ctx;
}
return null;
}
};
ctxSource.setUserDn("manager");
ctxSource.setPassword("password");
ctxSource.afterPropertiesSet();
this.ctxSource.setUserDn("manager");
this.ctxSource.setPassword("password");
this.ctxSource.afterPropertiesSet();
}
@Test
public void contextIsReturnedWhenNoControlsAreSetAndReconnectIsSuccessful() {
assertThat(ctxSource.getContext("user", "ignored")).isNotNull();
assertThat(this.ctxSource.getContext("user", "ignored")).isNotNull();
}
@Test(expected = UncategorizedLdapException.class)
public void standardExceptionIsPropagatedWhenExceptionRaisedAndNoControlsAreSet() throws Exception {
doThrow(new NamingException("some LDAP exception")).when(ctx).reconnect(any(Control[].class));
doThrow(new NamingException("some LDAP exception")).when(this.ctx).reconnect(any(Control[].class));
ctxSource.getContext("user", "ignored");
this.ctxSource.getContext("user", "ignored");
}
@Test(expected = PasswordPolicyException.class)
public void lockedPasswordPolicyControlRaisesPasswordPolicyException() throws Exception {
when(ctx.getResponseControls()).thenReturn(new Control[] {
when(this.ctx.getResponseControls()).thenReturn(new Control[] {
new PasswordPolicyResponseControl(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL) });
doThrow(new NamingException("locked message")).when(ctx).reconnect(any(Control[].class));
doThrow(new NamingException("locked message")).when(this.ctx).reconnect(any(Control[].class));
ctxSource.getContext("user", "ignored");
this.ctxSource.getContext("user", "ignored");
}
}
@@ -41,31 +41,31 @@ public class LdapAuthorityTests {
Map<String, List<String>> attributes = new HashMap<>();
attributes.put(SpringSecurityLdapTemplate.DN_KEY, Arrays.asList(DN));
attributes.put("mail", Arrays.asList("filip@ldap.test.org", "filip@ldap.test2.org"));
authority = new LdapAuthority("testRole", DN, attributes);
this.authority = new LdapAuthority("testRole", DN, attributes);
}
@Test
public void testGetDn() {
assertThat(authority.getDn()).isEqualTo(DN);
assertThat(authority.getAttributeValues(SpringSecurityLdapTemplate.DN_KEY)).isNotNull();
assertThat(authority.getAttributeValues(SpringSecurityLdapTemplate.DN_KEY)).hasSize(1);
assertThat(authority.getFirstAttributeValue(SpringSecurityLdapTemplate.DN_KEY)).isEqualTo(DN);
assertThat(this.authority.getDn()).isEqualTo(DN);
assertThat(this.authority.getAttributeValues(SpringSecurityLdapTemplate.DN_KEY)).isNotNull();
assertThat(this.authority.getAttributeValues(SpringSecurityLdapTemplate.DN_KEY)).hasSize(1);
assertThat(this.authority.getFirstAttributeValue(SpringSecurityLdapTemplate.DN_KEY)).isEqualTo(DN);
}
@Test
public void testGetAttributes() {
assertThat(authority.getAttributes()).isNotNull();
assertThat(authority.getAttributeValues("mail")).isNotNull();
assertThat(authority.getAttributeValues("mail")).hasSize(2);
assertThat(authority.getFirstAttributeValue("mail")).isEqualTo("filip@ldap.test.org");
assertThat(authority.getAttributeValues("mail").get(0)).isEqualTo("filip@ldap.test.org");
assertThat(authority.getAttributeValues("mail").get(1)).isEqualTo("filip@ldap.test2.org");
assertThat(this.authority.getAttributes()).isNotNull();
assertThat(this.authority.getAttributeValues("mail")).isNotNull();
assertThat(this.authority.getAttributeValues("mail")).hasSize(2);
assertThat(this.authority.getFirstAttributeValue("mail")).isEqualTo("filip@ldap.test.org");
assertThat(this.authority.getAttributeValues("mail").get(0)).isEqualTo("filip@ldap.test.org");
assertThat(this.authority.getAttributeValues("mail").get(1)).isEqualTo("filip@ldap.test2.org");
}
@Test
public void testGetAuthority() {
assertThat(authority.getAuthority()).isNotNull();
assertThat(authority.getAuthority()).isEqualTo("testRole");
assertThat(this.authority.getAuthority()).isNotNull();
assertThat(this.authority.getAuthority()).isEqualTo("testRole");
}
}