authenticateBasic
Wraps the inner route with Http Basic authentication support using a given Authenticator<T>
.
Description
Provides support for handling HTTP Basic Authentication.
Given a function returning an Optional<T>
with a value upon successful authentication and an empty Optional<T>
otherwise,
respectively applies the inner route or rejects the request with a AuthenticationFailedRejection
rejection,
which by default is mapped to an 401 Unauthorized
response.
Longer-running authentication tasks (like looking up credentials in a database) should use the authenticateBasicAsync variant of this directive which allows it to run without blocking routing layer of Akka HTTP, freeing it for other requests.
Standard HTTP-based authentication which uses the WWW-Authenticate
header containing challenge data and
Authorization
header for receiving credentials is implemented in subclasses of HttpAuthenticator
.
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
final Function<Optional<ProvidedCredentials>, Optional<String>> myUserPassAuthenticator =
credentials ->
credentials.filter(c -> c.verify("p4ssw0rd")).map(ProvidedCredentials::identifier);
final Route route = path("secured", () ->
authenticateBasic("secure site", myUserPassAuthenticator, userName ->
complete("The user is '" + userName + "'")
)
).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\"");
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\"");
Contents