authenticateBasicPFAsync
Signature
type AsyncAuthenticatorPF[T] = PartialFunction[Credentials, Future[T]]
def authenticateBasicPFAsync[T](realm: String, authenticator: AsyncAuthenticatorPF[T]): AuthenticationDirective[T]
Description
Wraps the inner route with Http Basic authentication support using a given AsyncAuthenticatorPF[T]
.
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
case class User(id: String)
def fetchUser(id: String): Future[User] = {
// some fancy logic to obtain a User
Future.successful(User(id))
}
val myUserPassAuthenticator: AsyncAuthenticatorPF[User] = {
case p @ Credentials.Provided(id) if p.verify("p4ssw0rd") =>
fetchUser(id)
}
val route =
Route.seal {
path("secured") {
authenticateBasicPFAsync(realm = "secure site", myUserPassAuthenticator) { user =>
complete(s"The user is '${user.id}'")
}
}
}
// tests:
Get("/secured") ~> route ~> check {
status shouldEqual StatusCodes.Unauthorized
responseAs[String] shouldEqual "The resource requires authentication, which was not supplied with the request"
header[`WWW-Authenticate`].get.challenges.head shouldEqual HttpChallenge("Basic", Some("secure site"), Map("charset" → "UTF-8"))
}
val validCredentials = BasicHttpCredentials("John", "p4ssw0rd")
Get("/secured") ~> addCredentials(validCredentials) ~> // adds Authorization header
route ~> check {
responseAs[String] shouldEqual "The user is 'John'"
}
val invalidCredentials = BasicHttpCredentials("Peter", "pan")
Get("/secured") ~>
addCredentials(invalidCredentials) ~> // adds Authorization header
route ~> check {
status shouldEqual StatusCodes.Unauthorized
responseAs[String] shouldEqual "The supplied authentication is invalid"
header[`WWW-Authenticate`].get.challenges.head shouldEqual HttpChallenge("Basic", Some("secure site"), Map("charset" → "UTF-8"))
}