authenticateBasicPF
Signature
Description
Wraps the inner route with Http Basic authentication support using a given AuthenticatorPF[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.
Longer-running authentication tasks (like looking up credentials in a database) should use authenticateBasicAsync
or authenticateBasicPFAsync if you prefer to use the PartialFunction
syntax.
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
val myUserPassAuthenticator: AuthenticatorPF[String] = {
case p @ Credentials.Provided(id) if p.verify("p4ssw0rd") => id
case p @ Credentials.Provided(id) if p.verify("p4ssw0rd-special") => s"$id-admin"
}
val route =
Route.seal {
path("secured") {
authenticateBasicPF(realm = "secure site", myUserPassAuthenticator) { userName =>
complete(s"The user is '$userName'")
}
}
}
// 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"))
}
val validCredentials = BasicHttpCredentials("John", "p4ssw0rd")
Get("/secured") ~> addCredentials(validCredentials) ~> // adds Authorization header
route ~> check {
responseAs[String] shouldEqual "The user is 'John'"
}
val validAdminCredentials = BasicHttpCredentials("John", "p4ssw0rd-special")
Get("/secured") ~> addCredentials(validAdminCredentials) ~> // adds Authorization header
route ~> check {
responseAs[String] shouldEqual "The user is 'John-admin'"
}
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"))
}
Contents