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);

    assertEquals(0, result.getAuthorities().size());

    dca.addAttributeValue("memberOf", "CN=Admin,CN=Users,DC=mydomain,DC=eu");

    result = provider.authenticate(joe);

    assertEquals(1, result.getAuthorities().size());
  }
 @Test(expected = LockedException.class)
 public void accountLockedIsCorrectlyMapped() {
   provider.contextFactory =
       createContextFactoryThrowing(new AuthenticationException(msg + "775, xxxx]"));
   provider.setConvertSubErrorCodesToExceptions(true);
   provider.authenticate(joe);
 }
 @Test(expected = BadCredentialsException.class)
 public void unknownErrorCodeIsCorrectlyMapped() {
   provider.contextFactory =
       createContextFactoryThrowing(new AuthenticationException(msg + "999, xxxx]"));
   provider.setConvertSubErrorCodesToExceptions(true);
   provider.authenticate(joe);
 }
  @Test
  public void passwordNeedsResetIsCorrectlyMapped() {
    final String dataCode = "773";
    provider.contextFactory =
        createContextFactoryThrowing(new AuthenticationException(msg + dataCode + ", xxxx]"));
    provider.setConvertSubErrorCodesToExceptions(true);

    thrown.expect(BadCredentialsException.class);
    thrown.expect(
        new BaseMatcher<BadCredentialsException>() {
          private Matcher<Object> causeInstance =
              CoreMatchers.instanceOf(ActiveDirectoryAuthenticationException.class);
          private Matcher<String> causeDataCode = CoreMatchers.equalTo(dataCode);

          public boolean matches(Object that) {
            Throwable t = (Throwable) that;
            ActiveDirectoryAuthenticationException cause =
                (ActiveDirectoryAuthenticationException) t.getCause();
            return causeInstance.matches(cause) && causeDataCode.matches(cause.getDataCode());
          }

          public void describeTo(Description desc) {
            desc.appendText("getCause() ");
            causeInstance.describeTo(desc);
            desc.appendText("getCause().getDataCode() ");
            causeDataCode.describeTo(desc);
          }
        });

    provider.authenticate(joe);
  }
  // SEC-2017
  @Test(expected = BadCredentialsException.class)
  public void noUserSearchCausesUsernameNotFound() throws Exception {
    DirContext ctx = mock(DirContext.class);
    when(ctx.getNameInNamespace()).thenReturn("");
    when(ctx.search(
            any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
        .thenReturn(new EmptyEnumeration<SearchResult>());

    provider.contextFactory = createContextFactoryReturning(ctx);

    provider.authenticate(joe);
  }
  @Test(expected = CredentialsExpiredException.class)
  public void expiredPasswordIsCorrectlyMapped() {
    provider.contextFactory =
        createContextFactoryThrowing(new AuthenticationException(msg + "532, xxxx]"));

    try {
      provider.authenticate(joe);
      fail();
    } catch (BadCredentialsException expected) {
    }

    provider.setConvertSubErrorCodesToExceptions(true);
    provider.authenticate(joe);
  }
  private void configureActiveDirectory(AuthenticationManagerBuilder auth) throws Exception {
    String domain = customProperties.getAdDomain();
    String url = customProperties.getAdUrl();
    if (domain != null) {
      ActiveDirectoryLdapAuthenticationProvider provider =
          new ActiveDirectoryLdapAuthenticationProvider(domain, url);
      provider.setUserDetailsContextMapper(userDetailsContextMapper());

      // Hm, this doesn't seem to have any effect, so handle the mapping in the
      // SeisoUserDetailsContextMapper.
      //			provider.setAuthoritiesMapper(grantedAuthoritiesMapper());

      auth.authenticationProvider(provider);
    }
  }
  @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);
  }
  @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("*****@*****.**", "password"));
  }
 @Test
 public void bindPrincipalIsCreatedCorrectly() throws Exception {
   assertEquals("*****@*****.**", provider.createBindPrincipal("joe"));
   assertEquals("*****@*****.**", provider.createBindPrincipal("*****@*****.**"));
 }
 @Test(expected = org.springframework.ldap.CommunicationException.class)
 public void nonAuthenticationExceptionIsConvertedToSpringLdapException() throws Exception {
   provider.contextFactory = createContextFactoryThrowing(new CommunicationException(msg));
   provider.authenticate(joe);
 }
 @Test(expected = BadCredentialsException.class)
 public void errorWithNoSubcodeIsHandledCleanly() throws Exception {
   provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg));
   provider.setConvertSubErrorCodesToExceptions(true);
   provider.authenticate(joe);
 }
 // SEC-2500
 @Test(expected = BadCredentialsException.class)
 public void sec2500PreventAnonymousBind() {
   provider.authenticate(new UsernamePasswordAuthenticationToken("rwinch", ""));
 }