public Object executeWithContext(DirContext ctx) throws NamingException { try { Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve); return new DirContextAdapter(attrs, LdapUtils.getFullDn(dn, ctx)); } catch (NameNotFoundException notFound) { throw new UsernameNotFoundException( "User " + username + " not found", notFound); } } });
private DirContextAdapter loadUserAsContext(final DistinguishedName dn, final String username) { return (DirContextAdapter) template.executeReadOnly(new ContextExecutor() { public Object executeWithContext(DirContext ctx) throws NamingException { try { Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve); return new DirContextAdapter(attrs, LdapUtils.getFullDn(dn, ctx)); } catch (NameNotFoundException notFound) { throw new UsernameNotFoundException( "User " + username + " not found", notFound); } } }); }
public Object executeWithContext(DirContext ctx) throws NamingException { Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve); // Object object = ctx.lookup(LdapUtils.getRelativeName(dn, ctx)); return new DirContextAdapter(attrs, new DistinguishedName(dn), new DistinguishedName(ctx.getNameInNamespace())); } });
@SuppressWarnings("unchecked") @Test(expected = IncorrectResultSizeDataAccessException.class) public void duplicateUserSearchCausesError() throws Exception { DirContext ctx = mock(DirContext.class); when(ctx.getNameInNamespace()).thenReturn(""); NamingEnumeration<SearchResult> searchResults = mock(NamingEnumeration.class); when(searchResults.hasMore()).thenReturn(true, true, false); SearchResult searchResult = mock(SearchResult.class); when(searchResult.getObject()).thenReturn(new DirContextAdapter("ou=1"), new DirContextAdapter("ou=2")); when(searchResults.next()).thenReturn(searchResult); when( ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class))).thenReturn(searchResults); provider.contextFactory = createContextFactoryReturning(ctx); provider.authenticate(joe); }
public Object executeWithContext(DirContext ctx) throws NamingException { Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve); // Object object = ctx.lookup(LdapUtils.getRelativeName(dn, ctx)); return new DirContextAdapter(attrs, new DistinguishedName(dn), new DistinguishedName(ctx.getNameInNamespace())); } });
@Test public void delegationToUserDetailsServiceReturnsCorrectRoles() throws Exception { UserDetailsService uds = mock(UserDetailsService.class); UserDetails user = mock(UserDetails.class); when(uds.loadUserByUsername("joe")).thenReturn(user); List authorities = AuthorityUtils.createAuthorityList("ROLE_USER"); when(user.getAuthorities()).thenReturn(authorities); UserDetailsServiceLdapAuthoritiesPopulator populator = new UserDetailsServiceLdapAuthoritiesPopulator( uds); Collection<? extends GrantedAuthority> auths = populator.getGrantedAuthorities( new DirContextAdapter(), "joe"); assertThat(auths).hasSize(1); assertThat(AuthorityUtils.authorityListToSet(auths).contains("ROLE_USER")).isTrue(); } }
public void createUser(UserDetails user) { DirContextAdapter ctx = new DirContextAdapter(); copyToContext(user, ctx); DistinguishedName dn = usernameMapper.buildDn(user.getUsername()); logger.debug("Creating new user '" + user.getUsername() + "' with DN '" + dn + "'"); template.bind(dn, ctx, null); // Check for any existing authorities which might be set for this DN and remove // them List<GrantedAuthority> authorities = getUserAuthorities(dn, user.getUsername()); if (authorities.size() > 0) { removeAuthorities(dn, authorities); } addAuthorities(dn, user.getAuthorities()); }
private void checkAuthentication(String rootDn, ActiveDirectoryLdapAuthenticationProvider provider) throws NamingException { DirContext ctx = mock(DirContext.class); when(ctx.getNameInNamespace()).thenReturn(""); DirContextAdapter dca = new DirContextAdapter(); SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes()); @SuppressWarnings("deprecation") DistinguishedName searchBaseDn = new DistinguishedName(rootDn); when( ctx.search(eq(searchBaseDn), any(String.class), any(Object[].class), any(SearchControls.class))).thenReturn( new MockNamingEnumeration(sr)).thenReturn(new MockNamingEnumeration(sr)); provider.contextFactory = createContextFactoryReturning(ctx); Authentication result = provider.authenticate(joe); assertThat(result.getAuthorities()).isEmpty(); dca.addAttributeValue("memberOf", "CN=Admin,CN=Users,DC=mydomain,DC=eu"); result = provider.authenticate(joe); assertThat(result.getAuthorities()).hasSize(1); }
public DirContextOperations authenticate(Authentication authentication) { DirContextAdapter ctx = new DirContextAdapter(); ctx.setAttributeValue("ou", "FROM_ENTRY"); String username = authentication.getName(); String password = (String) authentication.getCredentials(); if (username.equals("ben") && password.equals("benspassword")) { ctx.setDn(new DistinguishedName( "cn=ben,ou=people,dc=springframework,dc=org")); ctx.setAttributeValue("userPassword", "{SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ="); return ctx; } else if (username.equals("jen") && password.equals("")) { ctx.setDn(new DistinguishedName( "cn=jen,ou=people,dc=springframework,dc=org")); return ctx; } throw new BadCredentialsException("Authentication failed."); } }
@Test public void customSearchFilterIsUsedForSuccessfulAuthentication() throws Exception { // given String customSearchFilter = "(&(objectClass=user)(sAMAccountName={0}))"; DirContext ctx = mock(DirContext.class); when(ctx.getNameInNamespace()).thenReturn(""); DirContextAdapter dca = new DirContextAdapter(); SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes()); when( ctx.search(any(Name.class), eq(customSearchFilter), any(Object[].class), any(SearchControls.class))).thenReturn( new MockNamingEnumeration(sr)); ActiveDirectoryLdapAuthenticationProvider customProvider = new ActiveDirectoryLdapAuthenticationProvider( "mydomain.eu", "ldap://192.168.1.200/"); customProvider.contextFactory = createContextFactoryReturning(ctx); // when customProvider.setSearchFilter(customSearchFilter); Authentication result = customProvider.authenticate(joe); // then assertThat(result.isAuthenticated()).isTrue(); }
@Test public void mappingBackToContextMatchesOriginalData() { DirContextAdapter ctx1 = createUserContext(); DirContextAdapter ctx2 = new DirContextAdapter(); ctx1.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); ctx2.setDn(new DistinguishedName("ignored=ignored")); InetOrgPerson p = (InetOrgPerson) (new InetOrgPerson.Essence(ctx1)) .createUserDetails(); p.populateContext(ctx2); assertThat(ctx2).isEqualTo(ctx1); }
@Test public void testPasswordAttributeIsMappedCorrectly() throws Exception { LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); mapper.setPasswordAttributeName("myappsPassword"); BasicAttributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("myappsPassword", "mypassword".getBytes())); DirContextAdapter ctx = new DirContextAdapter(attrs, new DistinguishedName("cn=someName")); ctx.setAttributeValue("uid", "ani"); LdapUserDetails user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", AuthorityUtils.NO_AUTHORITIES); assertThat(user.getPassword()).isEqualTo("mypassword"); }
@Test public void correctAuthoritiesAreReturned() { DirContextAdapter userData = new DirContextAdapter(new DistinguishedName( "uid=joe")); LdapUserDetailsService service = new LdapUserDetailsService(new MockUserSearch( userData), new MockAuthoritiesPopulator()); service.setUserDetailsMapper(new LdapUserDetailsMapper()); UserDetails user = service.loadUserByUsername("doesntmatterwegetjoeanyway"); Set<String> authorities = AuthorityUtils .authorityListToSet(user.getAuthorities()); assertThat(authorities).hasSize(1); assertThat(authorities.contains("ROLE_FROM_POPULATOR")).isTrue(); }
@Test public void copyMatchesOriginalData() { DirContextAdapter ctx1 = createUserContext(); DirContextAdapter ctx2 = new DirContextAdapter(); ctx2.setDn(new DistinguishedName("ignored=ignored")); ctx1.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); InetOrgPerson p = (InetOrgPerson) (new InetOrgPerson.Essence(ctx1)) .createUserDetails(); InetOrgPerson p2 = (InetOrgPerson) new InetOrgPerson.Essence(p) .createUserDetails(); p2.populateContext(ctx2); assertThat(ctx2).isEqualTo(ctx1); }
@Test public void nullPopulatorConstructorReturnsEmptyAuthoritiesList() throws Exception { DirContextAdapter userData = new DirContextAdapter(new DistinguishedName( "uid=joe")); LdapUserDetailsService service = new LdapUserDetailsService(new MockUserSearch( userData)); UserDetails user = service.loadUserByUsername("doesntmatterwegetjoeanyway"); assertThat(user.getAuthorities()).isEmpty(); }
@Test public void testGivenNameAttributeNameMapping() throws Exception { attrs.put("givenName", "Marissa"); adapter = new DirContextAdapter(attrs, new LdapName("cn=marissa,ou=Users,dc=test,dc=com")); mapper.setGivenNameAttributeName("givenName"); ExtendedLdapUserImpl ldapUserDetails = getExtendedLdapUser(); Assert.assertThat(ldapUserDetails.getGivenName(), is("Marissa")); }
@Test public void testPhoneNumberAttributeNameMapping() throws Exception { attrs.put("phoneNumber", "8675309"); adapter = new DirContextAdapter(attrs, new LdapName("cn=marissa,ou=Users,dc=test,dc=com")); mapper.setPhoneNumberAttributeName("phoneNumber"); ExtendedLdapUserImpl ldapUserDetails = getExtendedLdapUser(); Assert.assertThat(ldapUserDetails.getPhoneNumber(), is("8675309")); }
@Test public void testFamilyNameAttributeNameMapping() throws Exception { attrs.put("lastName", "Lastnamerton"); adapter = new DirContextAdapter(attrs, new LdapName("cn=marissa,ou=Users,dc=test,dc=com")); mapper.setFamilyNameAttributeName("lastName"); ExtendedLdapUserImpl ldapUserDetails = getExtendedLdapUser(); Assert.assertThat(ldapUserDetails.getFamilyName(), is("Lastnamerton")); }
@Test public void testMultipleRoleAttributeValuesAreMappedToAuthorities() throws Exception { LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); mapper.setConvertToUpperCase(false); mapper.setRolePrefix(""); mapper.setRoleAttributes(new String[] { "userRole" }); DirContextAdapter ctx = new DirContextAdapter(); ctx.setAttributeValues("userRole", new String[] { "X", "Y", "Z" }); ctx.setAttributeValue("uid", "ani"); LdapUserDetailsImpl user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", AuthorityUtils.NO_AUTHORITIES); assertThat(user.getAuthorities()).hasSize(3); }
/** * SEC-303. Non-retrieved role attribute causes NullPointerException */ @Test public void testNonRetrievedRoleAttributeIsIgnored() throws Exception { LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); mapper.setRoleAttributes(new String[] { "userRole", "nonRetrievedAttribute" }); BasicAttributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("userRole", "x")); DirContextAdapter ctx = new DirContextAdapter(attrs, new DistinguishedName("cn=someName")); ctx.setAttributeValue("uid", "ani"); LdapUserDetailsImpl user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", AuthorityUtils.NO_AUTHORITIES); assertThat(user.getAuthorities()).hasSize(1); assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).contains("ROLE_X"); }