authenticateBasicPFAsync

Wraps the inner route with Http Basic authentication support using a given AsyncAuthenticatorPF<T>.

Description

Provides support for handling HTTP Basic Authentication.

Refer to authenticateBasic for a detailed description of this directive.

Its semantics are equivalent to authenticateBasicPF ’s, where not handling a case in the Partial Function (PF) leaves the request to be rejected with a AuthenticationFailedRejection rejection.

See Credentials and password timing attacks for details about verifying the secret.

Warning

Make sure to use basic authentication only over SSL/TLS because credentials are transferred in plaintext.

Example

class User {
  private final String id;
  public User(String id) {
    this.id = id;
  }
  public String getId() {
    return id;
  }
}

final PartialFunction<Optional<ProvidedCredentials>, CompletionStage<User>> myUserPassAuthenticator =
  new JavaPartialFunction<Optional<ProvidedCredentials>,CompletionStage<User>>() {
    @Override
    public CompletionStage<User> apply(Optional<ProvidedCredentials> opt, boolean isCheck) throws Exception {
      if (opt.filter(c -> (c != null) && c.verify("p4ssw0rd")).isPresent()) {
        if (isCheck) return CompletableFuture.completedFuture(null);
        else return CompletableFuture.completedFuture(new User(opt.get().identifier()));
      } else {
        throw noMatch();
      }
    }
  };

final Route route = path("secured", () ->
  authenticateBasicPFAsync("secure site", myUserPassAuthenticator, user ->
    complete("The user is '" + user.getId() + "'"))
).seal(system(), materializer());

// tests:
testRoute(route).run(HttpRequest.GET("/secured"))
  .assertStatusCode(StatusCodes.UNAUTHORIZED)
  .assertEntity("The resource requires authentication, which was not supplied with the request")
  .assertHeaderExists("WWW-Authenticate", "Basic realm=\"secure site\",charset=UTF-8");

final HttpCredentials validCredentials =
  BasicHttpCredentials.createBasicHttpCredentials("John", "p4ssw0rd");
testRoute(route).run(HttpRequest.GET("/secured").addCredentials(validCredentials))
  .assertEntity("The user is 'John'");

final HttpCredentials invalidCredentials =
  BasicHttpCredentials.createBasicHttpCredentials("Peter", "pan");
testRoute(route).run(HttpRequest.GET("/secured").addCredentials(invalidCredentials))
  .assertStatusCode(StatusCodes.UNAUTHORIZED)
  .assertEntity("The supplied authentication is invalid")
  .assertHeaderExists("WWW-Authenticate", "Basic realm=\"secure site\",charset=UTF-8");
The source code for this page can be found here.