Search in sources :

Example 66 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security by spring-projects.

the class BearerTokenServerAuthenticationEntryPointTests method commenceWhenNoSubscriberThenNothingHappens.

@Test
public void commenceWhenNoSubscriberThenNothingHappens() {
    this.entryPoint.commence(this.exchange, new BadCredentialsException(""));
    assertThat(getResponse().getHeaders()).isEmpty();
    assertThat(getResponse().getStatusCode()).isNull();
}
Also used : BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.jupiter.api.Test)

Example 67 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security by spring-projects.

the class AbstractLdapAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, () -> this.messages.getMessage("LdapAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported"));
    UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;
    String username = userToken.getName();
    String password = (String) authentication.getCredentials();
    if (!StringUtils.hasLength(username)) {
        throw new BadCredentialsException(this.messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username"));
    }
    if (!StringUtils.hasLength(password)) {
        throw new BadCredentialsException(this.messages.getMessage("AbstractLdapAuthenticationProvider.emptyPassword", "Empty Password"));
    }
    Assert.notNull(password, "Null password was supplied in authentication token");
    DirContextOperations userData = doAuthentication(userToken);
    UserDetails user = this.userDetailsContextMapper.mapUserFromContext(userData, authentication.getName(), loadUserAuthorities(userData, authentication.getName(), (String) authentication.getCredentials()));
    return createSuccessfulAuthentication(userToken, user);
}
Also used : UserDetails(org.springframework.security.core.userdetails.UserDetails) DirContextOperations(org.springframework.ldap.core.DirContextOperations) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 68 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security by spring-projects.

the class LdapUserDetailsManager method changePasswordUsingAttributeModification.

private void changePasswordUsingAttributeModification(DistinguishedName userDn, String oldPassword, String newPassword) {
    ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(this.passwordAttributeName, newPassword)) };
    if (oldPassword == null) {
        this.template.modifyAttributes(userDn, passwordChange);
        return;
    }
    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());
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword);
        // TODO: reconnect doesn't appear to actually change the credentials
        try {
            ctx.reconnect(null);
        } catch (javax.naming.AuthenticationException ex) {
            throw new BadCredentialsException("Authentication for password change failed.");
        }
        ctx.modifyAttributes(userDn, passwordChange);
        return null;
    });
}
Also used : BasicAttribute(javax.naming.directory.BasicAttribute) ModificationItem(javax.naming.directory.ModificationItem) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) LdapContext(javax.naming.ldap.LdapContext)

Example 69 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security by spring-projects.

the class PasswordComparisonAuthenticator method authenticate.

@Override
public DirContextOperations authenticate(final Authentication authentication) {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects");
    // locate the user and check the password
    DirContextOperations user = null;
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();
    SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());
    for (String userDn : getUserDns(username)) {
        try {
            user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
        } catch (NameNotFoundException ignore) {
            logger.trace(LogMessage.format("Failed to retrieve user with %s", userDn), ignore);
        }
        if (user != null) {
            break;
        }
    }
    if (user == null) {
        logger.debug(LogMessage.of(() -> "Failed to retrieve user with any user DNs " + getUserDns(username)));
    }
    if (user == null && getUserSearch() != null) {
        logger.trace("Searching for user using " + getUserSearch());
        user = getUserSearch().searchForUser(username);
        if (user == null) {
            logger.debug("Failed to find user using " + getUserSearch());
        }
    }
    if (user == null) {
        throw new UsernameNotFoundException("User not found: " + username);
    }
    if (logger.isTraceEnabled()) {
        logger.trace(LogMessage.format("Comparing password attribute '%s' for user '%s'", this.passwordAttributeName, user.getDn()));
    }
    if (this.usePasswordAttrCompare && isPasswordAttrCompare(user, password)) {
        logger.debug(LogMessage.format("Locally matched password attribute '%s' for user '%s'", this.passwordAttributeName, user.getDn()));
        return user;
    }
    if (isLdapPasswordCompare(user, ldapTemplate, password)) {
        logger.debug(LogMessage.format("LDAP-matched password attribute '%s' for user '%s'", this.passwordAttributeName, user.getDn()));
        return user;
    }
    throw new BadCredentialsException(this.messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SpringSecurityLdapTemplate(org.springframework.security.ldap.SpringSecurityLdapTemplate) DirContextOperations(org.springframework.ldap.core.DirContextOperations) NameNotFoundException(org.springframework.ldap.NameNotFoundException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 70 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security by spring-projects.

the class AuthenticationWebFilterTests method filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationFailThenUnauthorized.

@Test
public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationFailThenUnauthorized() {
    given(this.authenticationManager.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("failed")));
    given(this.authenticationManagerResolver.resolve(any())).willReturn(Mono.just(this.authenticationManager));
    this.filter = new AuthenticationWebFilter(this.authenticationManagerResolver);
    WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
    EntityExchangeResult<Void> result = client.get().uri("/").headers((headers) -> headers.setBasicAuth("test", "this")).exchange().expectStatus().isUnauthorized().expectHeader().valueMatches("WWW-Authenticate", "Basic realm=\"Realm\"").expectBody().isEmpty();
    assertThat(result.getResponseCookies()).isEmpty();
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) ServerWebExchangeMatcher(org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher) Mock(org.mockito.Mock) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) ReactiveAuthenticationManagerResolver(org.springframework.security.authentication.ReactiveAuthenticationManagerResolver) WebTestClientBuilder(org.springframework.security.test.web.reactive.server.WebTestClientBuilder) ServerSecurityContextRepository(org.springframework.security.web.server.context.ServerSecurityContextRepository) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) Mono(reactor.core.publisher.Mono) EntityExchangeResult(org.springframework.test.web.reactive.server.EntityExchangeResult) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) Mockito.never(org.mockito.Mockito.never) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) Authentication(org.springframework.security.core.Authentication) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.jupiter.api.Test)

Aggregations

BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)174 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)63 Authentication (org.springframework.security.core.Authentication)57 Test (org.junit.jupiter.api.Test)32 Test (org.junit.Test)26 AuthenticationException (org.springframework.security.core.AuthenticationException)24 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)22 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)21 UserDetails (org.springframework.security.core.userdetails.UserDetails)20 GrantedAuthority (org.springframework.security.core.GrantedAuthority)15 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)14 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)13 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)12 FilterChain (jakarta.servlet.FilterChain)10 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)10 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)9 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)7