public void setGroupSearchBase(String groupSearchBase) { this.groupSearchBase = new DistinguishedName(groupSearchBase); }
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())); } });
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())); } });
/** * Assembles the Distinguished Name that should be used the given username. */ public DistinguishedName buildDn(String username) { DistinguishedName dn = new DistinguishedName(userDnBase); dn.add(usernameAttribute, username); return dn; } }
/** * Creates a DN from a group name. * * @param group the name of the group * @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()); return dn; }
/** * Creates the user authority list from the values of the {@code memberOf} attribute * obtained from the user's Active Directory entry. */ @Override protected Collection<? extends GrantedAuthority> loadUserAuthorities( DirContextOperations userData, String username, String password) { String[] groups = userData.getStringAttributes("memberOf"); if (groups == null) { logger.debug("No values for 'memberOf' attribute."); return AuthorityUtils.NO_AUTHORITIES; } if (logger.isDebugEnabled()) { logger.debug("'memberOf' attribute values: " + Arrays.asList(groups)); } ArrayList<GrantedAuthority> authorities = new ArrayList<>( groups.length); for (String group : groups) { authorities.add(new SimpleGrantedAuthority(new DistinguishedName(group) .removeLast().getValue())); } return authorities; }
SearchControls searchControls, String base, String filter, Object[] params) throws NamingException { final DistinguishedName ctxBaseDn = new DistinguishedName( ctx.getNameInNamespace()); final DistinguishedName searchBaseDn = new DistinguishedName(base); final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn, filter, params, buildControls(searchControls));
/** * Gets the full dn of a name by prepending the name of the context it is relative to. * If the name already contains the base name, it is returned unaltered. */ public static DistinguishedName getFullDn(DistinguishedName dn, Context baseCtx) throws NamingException { DistinguishedName baseDn = new DistinguishedName(baseCtx.getNameInNamespace()); if (dn.contains(baseDn)) { return dn; } baseDn.append(dn); return baseDn; }
/** * Obtains the part of a DN relative to a supplied base context. * <p> * If the DN is "cn=bob,ou=people,dc=springframework,dc=org" and the base context name * is "ou=people,dc=springframework,dc=org" it would return "cn=bob". * </p> * * @param fullDn the DN * @param baseCtx the context to work out the name relative to. * * @return the * * @throws NamingException any exceptions thrown by the context are propagated. */ public static String getRelativeName(String fullDn, Context baseCtx) throws NamingException { String baseDn = baseCtx.getNameInNamespace(); if (baseDn.length() == 0) { return fullDn; } DistinguishedName base = new DistinguishedName(baseDn); DistinguishedName full = new DistinguishedName(fullDn); if (base.equals(full)) { return ""; } Assert.isTrue(full.startsWith(base), "Full DN does not start with base DN"); full.removeFirst(base); return full.toString(); }
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."); } }
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); }
@Test public void expectedPrincipalIsReturned() { LdapUserDetailsImpl.Essence user = new LdapUserDetailsImpl.Essence(); user.setUsername("joe"); user.setDn(new DistinguishedName("uid=joe,ou=users")); AuthenticationSource source = new SpringSecurityAuthenticationSource(); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(user.createUserDetails(), null)); assertThat(source.getPrincipal()).isEqualTo("uid=joe,ou=users"); } }
@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 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 nullDomainIsSupportedIfAuthenticatingWithFullUserPrincipal() throws Exception { provider = new ActiveDirectoryLdapAuthenticationProvider(null, "ldap://192.168.1.200/"); DirContext ctx = mock(DirContext.class); when(ctx.getNameInNamespace()).thenReturn(""); DirContextAdapter dca = new DirContextAdapter(); SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes()); when( ctx.search(eq(new DistinguishedName("DC=mydomain,DC=eu")), any(String.class), any(Object[].class), any(SearchControls.class))) .thenReturn(new MockNamingEnumeration(sr)); provider.contextFactory = createContextFactoryReturning(ctx); try { provider.authenticate(joe); fail("Expected BadCredentialsException for user with no domain information"); } catch (BadCredentialsException expected) { } provider.authenticate(new UsernamePasswordAuthenticationToken("joe@mydomain.eu", "password")); }
@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 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); }
/** * 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"); }
@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); }
private DirContextAdapter createUserContext() { DirContextAdapter ctx = new DirContextAdapter(); ctx.setDn(new DistinguishedName("ignored=ignored")); ctx.setAttributeValue("uid", "ghengis"); ctx.setAttributeValue("userPassword", "pillage"); ctx.setAttributeValue("carLicense", "HORS1"); ctx.setAttributeValue("cn", "Ghengis Khan"); ctx.setAttributeValue("description", "Scary"); ctx.setAttributeValue("destinationIndicator", "West"); ctx.setAttributeValue("displayName", "Ghengis McCann"); ctx.setAttributeValue("givenName", "Ghengis"); ctx.setAttributeValue("homePhone", "+467575436521"); ctx.setAttributeValue("initials", "G"); ctx.setAttributeValue("employeeNumber", "00001"); ctx.setAttributeValue("homePostalAddress", "Steppes"); ctx.setAttributeValue("mail", "ghengis@mongolia"); ctx.setAttributeValue("mobile", "always"); ctx.setAttributeValue("o", "Hordes"); ctx.setAttributeValue("ou", "Horde1"); ctx.setAttributeValue("postalAddress", "On the Move"); ctx.setAttributeValue("postalCode", "Changes Frequently"); ctx.setAttributeValue("roomNumber", "Yurt 1"); ctx.setAttributeValue("roomNumber", "Yurt 1"); ctx.setAttributeValue("sn", "Khan"); ctx.setAttributeValue("street", "Westward Avenue"); ctx.setAttributeValue("telephoneNumber", "+442075436521"); return ctx; }