Files
pip/libs/http_server/pihttpserverbearerauth.cpp

38 lines
1.1 KiB
C++

#include "pihttpserverbearerauth.h"
#include "piliterals_string.h"
namespace {
bool parseBearer(const PIString & auth_header, PIString & token) {
if (auth_header.left(7).toLowerCase() != "bearer "_a) return false;
PIString rest = auth_header.mid(7).trimmed();
if (rest.isEmpty()) return false;
token = rest;
return true;
}
} // namespace
PIHTTPServerBearerAuth::PIHTTPServerBearerAuth() {
auth_realm = "Restricted"_a;
}
PIHTTP::MessageMutable PIHTTPServerBearerAuth::accessDeniedReply(const PIHTTP::MessageConst &) {
return PIHTTP::MessageMutable::fromCode(PIHTTP::Code::Unauthorized)
.addHeader(PIHTTP::Header::WWWAuthenticate, "Bearer realm=\"%1\""_a.arg(auth_realm))
.setBody(PIByteArray::fromAscii("Authorization required"));
}
PIHTTP::AuthInfo PIHTTPServerBearerAuth::authenticate(const PIHTTP::MessageConst & request) {
if (!callback_auth) return PIHTTP::AuthInfo();
PIString header = request.headers().value(PIHTTP::Header::Authorization, "");
PIString token;
if (!parseBearer(header, token)) return PIHTTP::AuthInfo();
return callback_auth(token);
}