extractCredentials

Signature

def extractCredentials: Directive1[Option[HttpCredentials]]

Description

Extracts the potentially present HttpCredentialsHttpCredentials provided with the request’s AuthorizationAuthorization header, which can be then used to implement some custom authentication or authorization logic.

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

Example

Scala
sourceval route =
  extractCredentials { creds =>
    complete {
      creds match {
        case Some(c) => "Credentials: " + c
        case _       => "No credentials"
      }
    }
  }

// tests:
val johnsCred = BasicHttpCredentials("John", "p4ssw0rd")
Get("/") ~> addCredentials(johnsCred) ~> // adds Authorization header
  route ~> check {
    responseAs[String] shouldEqual "Credentials: Basic Sm9objpwNHNzdzByZA=="
  }

Get("/") ~> route ~> check {
  responseAs[String] shouldEqual "No credentials"
}
Java
sourceimport akka.http.javadsl.model.headers.HttpCredentials;

import static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.extractCredentials;

final Route route = extractCredentials(optCreds -> {
  if (optCreds.isPresent()) {
    return complete("Credentials: " + optCreds.get());
  } else {
    return complete("No credentials");
  }
});

// tests:
final HttpCredentials johnsCred =
  BasicHttpCredentials.createBasicHttpCredentials("John", "p4ssw0rd");
testRoute(route).run(HttpRequest.GET("/").addCredentials(johnsCred))
  .assertEntity("Credentials: Basic Sm9objpwNHNzdzByZA==");

testRoute(route).run(HttpRequest.GET("/"))
  .assertEntity("No credentials");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.