Credentials { public static Optional<Credentials> readFrom(HttpServletRequest request) { String authorizationHeader = request.getHeader("Authorization"); if (!StringUtils.isEmpty(authorizationHeader) && authorizationHeader.contains("Basic")) { String credentials = authorizationHeader.substring(6, authorizationHeader.length()); Optional<String> decodedCredentials = base64Decode(credentials); String[] decodedCredentialParts = decodedCredentials .map(s1 -> s1.split(":", 2)) .orElse(new String[0]); if (decodedCredentialParts.length >= 2 && !decodedCredentialParts[0].isEmpty() && !decodedCredentialParts[1].isEmpty()) { return Optional.of(new Credentials(decodedCredentialParts[0], decodedCredentialParts[1])); } } return Optional.empty(); } Credentials(String username, String password); String getUsername(); String getPassword(); static Optional<Credentials> readFrom(HttpServletRequest request);  }
@Test public void shouldReturnEmptyCredentialsIfHeaderDoesNotExist() { final Optional<Credentials> credentials = Credentials.readFrom(httpServletRequest); assertThat(credentials.isPresent(), is(false)); }
@Test public void shouldReturnEmptyCredentialsIfPasswordNotSet() { mockHttpServletRequestWithAuthentication("someUsername:"); final Optional<Credentials> credentials = Credentials.readFrom(httpServletRequest); assertThat(credentials.isPresent(), is(false)); }
@Test public void shouldReturnEmptyCredentialsIfUsernameNotSet() { mockHttpServletRequestWithAuthentication(":password"); final Optional<Credentials> credentials = Credentials.readFrom(httpServletRequest); assertThat(credentials.isPresent(), is(false)); }
@Test public void shouldReturnEmptyCredentialsIfAnotherAuthorizationSchemeThanBasicIsUsed() { when(httpServletRequest.getHeader("Authorization")) .thenReturn( "Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"); final Optional<Credentials> credentials = Credentials.readFrom(httpServletRequest); assertThat(credentials.isPresent(), is(false)); }
@Test public void shouldReturnEmptyCredentialsIfColonDoesNotExist() { mockHttpServletRequestWithAuthentication("userpass"); final Optional<Credentials> credentials = Credentials.readFrom(httpServletRequest); assertThat(credentials.isPresent(), is(false)); }
@Test public void shouldReturnEmptyCredentialsIfAuthenticationNotBasic() { when(httpServletRequest.getHeader("Authorization")) .thenReturn("Bearer someToken"); final Optional<Credentials> credentials = Credentials.readFrom(httpServletRequest); assertThat(credentials.isPresent(), is(false)); }