authenticateBasicPFAsync

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.

警告

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

§Example

  1. class User {
  2. private final String id;
  3. public User(String id) {
  4. this.id = id;
  5. }
  6. public String getId() {
  7. return id;
  8. }
  9. }
  10.  
  11. final PartialFunction<Optional<ProvidedCredentials>, CompletionStage<User>> myUserPassAuthenticator =
  12. new JavaPartialFunction<Optional<ProvidedCredentials>,CompletionStage<User>>() {
  13. @Override
  14. public CompletionStage<User> apply(Optional<ProvidedCredentials> opt, boolean isCheck) throws Exception {
  15. if (opt.filter(c -> (c != null) && c.verify("p4ssw0rd")).isPresent()) {
  16. if (isCheck) return CompletableFuture.completedFuture(null);
  17. else return CompletableFuture.completedFuture(new User(opt.get().identifier()));
  18. } else {
  19. throw noMatch();
  20. }
  21. }
  22. };
  23.  
  24. final Route route = path("secured", () ->
  25. authenticateBasicPFAsync("secure site", myUserPassAuthenticator, user ->
  26. complete("The user is '" + user.getId() + "'"))
  27. ).seal(system(), materializer());
  28.  
  29. // tests:
  30. testRoute(route).run(HttpRequest.GET("/secured"))
  31. .assertStatusCode(StatusCodes.UNAUTHORIZED)
  32. .assertEntity("The resource requires authentication, which was not supplied with the request")
  33. .assertHeaderExists("WWW-Authenticate", "Basic realm=\"secure site\"");
  34.  
  35. final HttpCredentials validCredentials =
  36. BasicHttpCredentials.createBasicHttpCredentials("John", "p4ssw0rd");
  37. testRoute(route).run(HttpRequest.GET("/secured").addCredentials(validCredentials))
  38. .assertEntity("The user is 'John'");
  39.  
  40. final HttpCredentials invalidCredentials =
  41. BasicHttpCredentials.createBasicHttpCredentials("Peter", "pan");
  42. testRoute(route).run(HttpRequest.GET("/secured").addCredentials(invalidCredentials))
  43. .assertStatusCode(StatusCodes.UNAUTHORIZED)
  44. .assertEntity("The supplied authentication is invalid")
  45. .assertHeaderExists("WWW-Authenticate", "Basic realm=\"secure site\"");