BcryptAuthenticator implements Authenticator<BasicCredentials, User> { @Override public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException { User user = null; String username = credentials.getUsername(); if (!User.isSanitizedUsername(username)) { logger.info("Username: {} must match pattern: {}", username, User.USERNAME_PATTERN); return Optional.empty(); } String password = credentials.getPassword(); Optional<String> optionalHashedPwForUser = userDAO.getHashedPassword(username); if (checkPassword(password, optionalHashedPwForUser)) { user = User.named(username); } return Optional.ofNullable(user); } BcryptAuthenticator(UserDAO userDAO); @Override Optional<User> authenticate(BasicCredentials credentials); static String hashPassword(String password);  }
@Test public void bcryptAuthenticatorCreatesUserOnSuccess() throws Exception { when(userDAO.getHashedPassword("sysadmin")) .thenReturn(Optional.of(hashedPass)); User user = bcryptAuthenticator.authenticate(new BasicCredentials("sysadmin", "validpass")) .orElseThrow(RuntimeException::new); assertThat(user).isEqualTo(User.named("sysadmin")); }
@Test public void bcryptAuthenticatorFailsForBadPassword() throws Exception { when(userDAO.getHashedPassword("sysadmin")) .thenReturn(Optional.of(hashedPass)); Optional<User> missingUser = bcryptAuthenticator.authenticate(new BasicCredentials("sysadmin", "badpass")); assertThat(missingUser).isEmpty(); }
@Test public void bcryptAuthenticatorFailsForBadUser() throws Exception { when(userDAO.getHashedPassword("invaliduser")) .thenReturn(Optional.empty()); Optional<User> missingUser = bcryptAuthenticator.authenticate(new BasicCredentials("invaliduser", "validpass")); assertThat(missingUser).isEmpty(); }
@Test public void bcryptAuthenticatorRejectsInvalidUsername() throws Exception { String crazyUsername = "sysadmin)`~!@#$%^&*()+=[]{}\\|;:'\",<>?/\r\n\t"; Optional<User> missingUser = bcryptAuthenticator.authenticate(new BasicCredentials(crazyUsername, "validpass")); assertThat(missingUser).isEmpty(); }