Support Handling Javax-based Bind Exceptions

Closes gh-3834
This commit is contained in:
Josh Cummings
2024-06-17 16:13:14 -06:00
parent fd1246a0b0
commit ef5c1a72db
2 changed files with 61 additions and 8 deletions

View File

@@ -16,12 +16,19 @@
package org.springframework.security.ldap.authentication;
import javax.naming.Name;
import javax.naming.ldap.LdapContext;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.AuthenticationException;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.support.BaseLdapPathContextSource;
import org.springframework.ldap.support.LdapUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
@@ -34,6 +41,10 @@ import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
/**
* Tests for {@link BindAuthenticator}.
@@ -142,4 +153,23 @@ public class BindAuthenticatorTests {
assertThat(this.authenticator.getUserDns("Joe").get(0)).isEqualTo("cn=Joe,ou=people");
}
@Test
public void setAlsoHandleJavaxNamingBindExceptionsWhenTrueThenHandles() throws Exception {
BaseLdapPathContextSource contextSource = spy(this.contextSource);
BindAuthenticator authenticator = new BindAuthenticator(contextSource);
authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
LdapContext dirContext = mock(LdapContext.class);
given(dirContext.getAttributes(any(Name.class), any())).willThrow(new javax.naming.AuthenticationException("exception"));
Name fullDn = LdapUtils.newLdapName("uid=bob,ou=people").addAll(0, contextSource.getBaseLdapPath());
given(contextSource.getContext(fullDn.toString(), (String) this.bob.getCredentials())).willReturn(dirContext);
authenticator.setAlsoHandleJavaxNamingBindExceptions(true);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(authenticateBob(authenticator));
authenticator.setAlsoHandleJavaxNamingBindExceptions(false);
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(authenticateBob(authenticator))
.withCauseInstanceOf(javax.naming.AuthenticationException.class);
}
private ThrowingCallable authenticateBob(BindAuthenticator authenticator) {
return () -> authenticator.authenticate(this.bob);
}
}