OAuth20Credentials.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. #include "Poco/Net/OAuth20Credentials.h"
  14. #include "Poco/Net/HTTPRequest.h"
  15. #include "Poco/Net/NetException.h"
  16. #include "Poco/String.h"
  17. namespace Poco {
  18. namespace Net {
  19. const std::string OAuth20Credentials::SCHEME = "Bearer";
  20. OAuth20Credentials::OAuth20Credentials():
  21. _scheme(SCHEME)
  22. {
  23. }
  24. OAuth20Credentials::OAuth20Credentials(const std::string& bearerToken):
  25. _bearerToken(bearerToken),
  26. _scheme(SCHEME)
  27. {
  28. }
  29. OAuth20Credentials::OAuth20Credentials(const std::string& bearerToken, const std::string& scheme):
  30. _bearerToken(bearerToken),
  31. _scheme(scheme)
  32. {
  33. }
  34. OAuth20Credentials::OAuth20Credentials(const HTTPRequest& request):
  35. _scheme(SCHEME)
  36. {
  37. extractBearerToken(request);
  38. }
  39. OAuth20Credentials::OAuth20Credentials(const HTTPRequest& request, const std::string& scheme):
  40. _scheme(scheme)
  41. {
  42. extractBearerToken(request);
  43. }
  44. OAuth20Credentials::~OAuth20Credentials()
  45. {
  46. }
  47. void OAuth20Credentials::setBearerToken(const std::string& bearerToken)
  48. {
  49. _bearerToken = bearerToken;
  50. }
  51. void OAuth20Credentials::setScheme(const std::string& scheme)
  52. {
  53. _scheme = scheme;
  54. }
  55. void OAuth20Credentials::authenticate(HTTPRequest& request)
  56. {
  57. std::string auth(_scheme);
  58. auth += ' ';
  59. auth += _bearerToken;
  60. request.set(HTTPRequest::AUTHORIZATION, auth);
  61. }
  62. void OAuth20Credentials::extractBearerToken(const HTTPRequest& request)
  63. {
  64. if (request.hasCredentials())
  65. {
  66. std::string authScheme;
  67. std::string authInfo;
  68. request.getCredentials(authScheme, authInfo);
  69. if (icompare(authScheme, _scheme) == 0)
  70. {
  71. _bearerToken = authInfo;
  72. }
  73. else throw NotAuthenticatedException("No bearer token in Authorization header", authScheme);
  74. }
  75. else throw NotAuthenticatedException("No Authorization header found");
  76. }
  77. } } // namespace Poco::Net