void received(const x::http::requestimpl &req, bool hasbody) { std::set<std::string> auths; req.get_basic_auth(req.www_authorization, [&] (const std::string &auth) { auths.insert(auth); }); if (auths.find("citizenkane:rosebud") == auths.end()) x::http::responseimpl::throw_unauthorized(x::http::auth::basic, "Auth Realm"); // ... }
The get_basic_auth
() method decodes any
basic authentication scheme headers present in a request.
The first parameter should be
x::http::requestimpl::www_authorization
if
the application implements an ordinary HTTP server,
or
x::http::requestimpl::proxy_authorization
if the
application implements an HTTP proxy.
The second parameter is a lambda or a functor that gets invoked
with the decoded “userid:password” string. The functor may
be called more than once if the request includes multiple basic
authorization headers. Although this is allowed by RFC 2617, this is
rare in practice. There will usually be just one, but this approach
supports multiple challenges, and it's up to the application to figure out
what to do in that case. This example is happy if one of them
was the userid “citizenkane” and the password
“rosebud”.
x::http::responseimpl::throw_unauthorized
()
throws an exception that responds to the original request with an
authentication challenge.
x::http::responseimpl::throw_proxy_authentication_required
()
sends a proxy authentication challenge response. In all other
respects these two functions are the same.
x::http::responseimpl::throw_unauthorized
()
and
x::http::responseimpl::throw_proxy_authentication_required
()
takes the following parameters:
An optional
x::http::httpver_t
that sets the response protocol version.
One or more challenges. Currently, multiple challenges are sent as separate headers in the response. Although RFC 2617 allows combining multiple challenges into a single header, at press time this does not work with many buggy HTTP clients. This may change in the future.
Each challenge consists of two parameters,
an authentication scheme (x::http::auth::basic
or x::http::auth::digest
) a
std::string
authentication realm,
followed by an optional list of scheme parameters: each one is a
a tuple of a
x::http::responseimpl::auth_param
and a std::string
, the value of the parameter.
An individual challenge can also be given as a
x::http::responseimpl::challenge_info
object instance.
Instead of a variadic challenge list,
x::http::responseimpl::throw_unauthorized
()
and
x::http::responseimpl::throw_proxy_authentication_required
()
also take a single parameter consisting of a (non-empty)
std::list<x::http::responseimpl::challenge_info;>
.
The above example shows the ordinary case of a boring basic authentication
scheme, just an x::http::auth::basic
, and some
arbitrary authentication realm label.
The HTTP client displays the realm label when
prompting for authentication.