Search in sources :

Example 71 with BadCredentialsException

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

the class AuthenticationWebFilterTests method filterWhenDefaultsAndAuthenticationFailThenUnauthorized.

@Test
public void filterWhenDefaultsAndAuthenticationFailThenUnauthorized() {
    given(this.authenticationManager.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("failed")));
    this.filter = new AuthenticationWebFilter(this.authenticationManager);
    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)

Example 72 with BadCredentialsException

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

the class BearerTokenAuthenticationEntryPointTests method commenceWhenNoBearerTokenErrorThenStatus401AndAuthHeader.

@Test
public void commenceWhenNoBearerTokenErrorThenStatus401AndAuthHeader() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    this.authenticationEntryPoint.commence(request, response, new BadCredentialsException("test"));
    assertThat(response.getStatus()).isEqualTo(401);
    assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer");
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 73 with BadCredentialsException

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

the class DigestAuthenticationFilter method doFilter.

private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    String header = request.getHeader("Authorization");
    if (header == null || !header.startsWith("Digest ")) {
        chain.doFilter(request, response);
        return;
    }
    logger.debug(LogMessage.format("Digest Authorization header received from user agent: %s", header));
    DigestData digestAuth = new DigestData(header);
    try {
        digestAuth.validateAndDecode(this.authenticationEntryPoint.getKey(), this.authenticationEntryPoint.getRealmName());
    } catch (BadCredentialsException ex) {
        fail(request, response, ex);
        return;
    }
    // Lookup password for presented username. N.B. DAO-provided password MUST be
    // clear text - not encoded/salted (unless this instance's passwordAlreadyEncoded
    // property is 'false')
    boolean cacheWasUsed = true;
    UserDetails user = this.userCache.getUserFromCache(digestAuth.getUsername());
    String serverDigestMd5;
    try {
        if (user == null) {
            cacheWasUsed = false;
            user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
            if (user == null) {
                throw new AuthenticationServiceException("AuthenticationDao returned null, which is an interface contract violation");
            }
            this.userCache.putUserInCache(user);
        }
        serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
        // If digest is incorrect, try refreshing from backend and recomputing
        if (!serverDigestMd5.equals(digestAuth.getResponse()) && cacheWasUsed) {
            logger.debug("Digest comparison failure; trying to refresh user from DAO in case password had changed");
            user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
            this.userCache.putUserInCache(user);
            serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
        }
    } catch (UsernameNotFoundException ex) {
        String message = this.messages.getMessage("DigestAuthenticationFilter.usernameNotFound", new Object[] { digestAuth.getUsername() }, "Username {0} not found");
        fail(request, response, new BadCredentialsException(message));
        return;
    }
    // If digest is still incorrect, definitely reject authentication attempt
    if (!serverDigestMd5.equals(digestAuth.getResponse())) {
        logger.debug(LogMessage.format("Expected response: '%s' but received: '%s'; is AuthenticationDao returning clear text passwords?", serverDigestMd5, digestAuth.getResponse()));
        String message = this.messages.getMessage("DigestAuthenticationFilter.incorrectResponse", "Incorrect response");
        fail(request, response, new BadCredentialsException(message));
        return;
    }
    // but the request was otherwise appearing to be valid
    if (digestAuth.isNonceExpired()) {
        String message = this.messages.getMessage("DigestAuthenticationFilter.nonceExpired", "Nonce has expired/timed out");
        fail(request, response, new NonceExpiredException(message));
        return;
    }
    logger.debug(LogMessage.format("Authentication success for user: '%s' with response: '%s'", digestAuth.getUsername(), digestAuth.getResponse()));
    Authentication authentication = createSuccessfulAuthentication(request, user);
    SecurityContext context = SecurityContextHolder.createEmptyContext();
    context.setAuthentication(authentication);
    SecurityContextHolder.setContext(context);
    chain.doFilter(request, response);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException)

Example 74 with BadCredentialsException

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

the class SubjectDnX509PrincipalExtractor method extractPrincipal.

@Override
public Object extractPrincipal(X509Certificate clientCert) {
    // String subjectDN = clientCert.getSubjectX500Principal().getName();
    String subjectDN = clientCert.getSubjectDN().getName();
    this.logger.debug(LogMessage.format("Subject DN is '%s'", subjectDN));
    Matcher matcher = this.subjectDnPattern.matcher(subjectDN);
    if (!matcher.find()) {
        throw new BadCredentialsException(this.messages.getMessage("SubjectDnX509PrincipalExtractor.noMatching", new Object[] { subjectDN }, "No matching pattern was found in subject DN: {0}"));
    }
    Assert.isTrue(matcher.groupCount() == 1, "Regular expression must contain a single group ");
    String username = matcher.group(1);
    this.logger.debug(LogMessage.format("Extracted Principal name is '%s'", username));
    return username;
}
Also used : Matcher(java.util.regex.Matcher) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 75 with BadCredentialsException

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

the class BasicAuthenticationConverter method convert.

@Override
public UsernamePasswordAuthenticationToken convert(HttpServletRequest request) {
    String header = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (header == null) {
        return null;
    }
    header = header.trim();
    if (!StringUtils.startsWithIgnoreCase(header, AUTHENTICATION_SCHEME_BASIC)) {
        return null;
    }
    if (header.equalsIgnoreCase(AUTHENTICATION_SCHEME_BASIC)) {
        throw new BadCredentialsException("Empty basic authentication token");
    }
    byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8);
    byte[] decoded = decode(base64Token);
    String token = new String(decoded, getCredentialsCharset(request));
    int delim = token.indexOf(":");
    if (delim == -1) {
        throw new BadCredentialsException("Invalid basic authentication token");
    }
    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(token.substring(0, delim), token.substring(delim + 1));
    result.setDetails(this.authenticationDetailsSource.buildDetails(request));
    return result;
}
Also used : UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

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