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();
}
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");
}
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);
}
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;
}
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;
}
Aggregations