| 1 | // |
|---|---|
| 2 | // OAuth20Credentials.cpp |
| 3 | // |
| 4 | // Library: Net |
| 5 | // Package: OAuth |
| 6 | // Module: OAuth20Credentials |
| 7 | // |
| 8 | // Copyright (c) 2014, Applied Informatics Software Engineering GmbH. |
| 9 | // and Contributors. |
| 10 | // |
| 11 | // SPDX-License-Identifier: BSL-1.0 |
| 12 | // |
| 13 | |
| 14 | |
| 15 | #include "Poco/Net/OAuth20Credentials.h" |
| 16 | #include "Poco/Net/HTTPRequest.h" |
| 17 | #include "Poco/Net/NetException.h" |
| 18 | #include "Poco/String.h" |
| 19 | |
| 20 | |
| 21 | namespace Poco { |
| 22 | namespace Net { |
| 23 | |
| 24 | |
| 25 | const std::string OAuth20Credentials::SCHEME = "Bearer"; |
| 26 | |
| 27 | |
| 28 | OAuth20Credentials::OAuth20Credentials(): |
| 29 | _scheme(SCHEME) |
| 30 | { |
| 31 | } |
| 32 | |
| 33 | |
| 34 | OAuth20Credentials::OAuth20Credentials(const std::string& bearerToken): |
| 35 | _bearerToken(bearerToken), |
| 36 | _scheme(SCHEME) |
| 37 | { |
| 38 | } |
| 39 | |
| 40 | |
| 41 | OAuth20Credentials::OAuth20Credentials(const std::string& bearerToken, const std::string& scheme): |
| 42 | _bearerToken(bearerToken), |
| 43 | _scheme(scheme) |
| 44 | { |
| 45 | } |
| 46 | |
| 47 | |
| 48 | OAuth20Credentials::OAuth20Credentials(const HTTPRequest& request): |
| 49 | _scheme(SCHEME) |
| 50 | { |
| 51 | extractBearerToken(request); |
| 52 | } |
| 53 | |
| 54 | |
| 55 | OAuth20Credentials::OAuth20Credentials(const HTTPRequest& request, const std::string& scheme): |
| 56 | _scheme(scheme) |
| 57 | { |
| 58 | extractBearerToken(request); |
| 59 | } |
| 60 | |
| 61 | |
| 62 | OAuth20Credentials::~OAuth20Credentials() |
| 63 | { |
| 64 | } |
| 65 | |
| 66 | |
| 67 | void OAuth20Credentials::setBearerToken(const std::string& bearerToken) |
| 68 | { |
| 69 | _bearerToken = bearerToken; |
| 70 | } |
| 71 | |
| 72 | |
| 73 | void OAuth20Credentials::setScheme(const std::string& scheme) |
| 74 | { |
| 75 | _scheme = scheme; |
| 76 | } |
| 77 | |
| 78 | |
| 79 | void OAuth20Credentials::authenticate(HTTPRequest& request) |
| 80 | { |
| 81 | std::string auth(_scheme); |
| 82 | auth += ' '; |
| 83 | auth += _bearerToken; |
| 84 | request.set(HTTPRequest::AUTHORIZATION, auth); |
| 85 | } |
| 86 | |
| 87 | |
| 88 | void OAuth20Credentials::extractBearerToken(const HTTPRequest& request) |
| 89 | { |
| 90 | if (request.hasCredentials()) |
| 91 | { |
| 92 | std::string authScheme; |
| 93 | std::string authInfo; |
| 94 | request.getCredentials(authScheme, authInfo); |
| 95 | if (icompare(authScheme, _scheme) == 0) |
| 96 | { |
| 97 | _bearerToken = authInfo; |
| 98 | } |
| 99 | else throw NotAuthenticatedException("No bearer token in Authorization header", authScheme); |
| 100 | } |
| 101 | else throw NotAuthenticatedException("No Authorization header found"); |
| 102 | } |
| 103 | |
| 104 | |
| 105 | } } // namespace Poco::Net |
| 106 |