Skip to content

Commit 0371816

Browse files
committed
Feat: Add method to extract HTTP Bearer token from Authorization header.
1 parent 2d573ad commit 0371816

File tree

4 files changed

+27
-1
lines changed

4 files changed

+27
-1
lines changed

include/pistache/http_header.h

+4
Original file line numberDiff line numberDiff line change
@@ -479,11 +479,15 @@ namespace Pistache::Http::Header
479479
// Get decoded user ID and password if basic method was used...
480480
std::string getBasicUser() const;
481481
std::string getBasicPassword() const;
482+
std::string getBearerToken() const;
482483

483484
// Set encoded user ID and password for basic method...
484485
void setBasicUserPassword(const std::string& User,
485486
const std::string& Password);
486487

488+
489+
void setBearertoken(const std::string& token);
490+
487491
void parse(const std::string& data) override;
488492
void write(std::ostream& os) const override;
489493

src/common/http_header.cc

+10
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,16 @@ namespace Pistache::Http::Header
450450
return true;
451451
}
452452

453+
std::string Authorization::getBearerToken() const
454+
{
455+
// Verify bearer authorization method was used...
456+
if (!hasMethod<Authorization::Method::Bearer>())
457+
throw std::runtime_error("Authorization header does not use Bearer method.");
458+
459+
const std::string token(value_.begin() + std::string("Bearer ").length(), value_.end());
460+
return token;
461+
}
462+
453463
// Get decoded user ID if basic method was used...
454464
std::string Authorization::getBasicUser() const
455465
{

tests/headers_test.cc

+12
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,7 @@ TEST(headers_test, authorization_basic_test)
427427
// Verify it decoded correctly...
428428
ASSERT_EQ(au.getBasicUser(), "Aladdin");
429429
ASSERT_EQ(au.getBasicPassword(), "OpenSesame");
430+
EXPECT_ANY_THROW( au.getBearerToken() );
430431
}
431432

432433
TEST(headers_test, authorization_bearer_test)
@@ -458,6 +459,17 @@ TEST(headers_test, authorization_bearer_test)
458459
"eyJleHAiOjE1NzA2MzA0MDcsImlhdCI6MTU3MDU0NDAwNywibmFtZSI6IkFkbWluIE5hbWUi"
459460
"LCJzYW1wbGUiOiJUZXN0In0.zLTAAnBftlqccsU-4mL69P4tQl3VhcglMg-"
460461
"d0131JxqX4xSZLlO5xMRrCPBgn_00OxKJ9CQdnpjpuzblNQd2-A");
462+
463+
EXPECT_ANY_THROW(au.getBasicUser() );
464+
EXPECT_ANY_THROW(au.getBasicPassword() );
465+
466+
ASSERT_EQ(au.getBearerToken(),
467+
"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXUyJ9."
468+
"eyJleHAiOjE1NzA2MzA0MDcsImlhdCI6MTU3MDU0NDAwNywibmFtZSI6IkFkbWluIE5hbWUi"
469+
"LCJzYW1wbGUiOiJUZXN0In0.zLTAAnBftlqccsU-4mL69P4tQl3VhcglMg-"
470+
"d0131JxqX4xSZLlO5xMRrCPBgn_00OxKJ9CQdnpjpuzblNQd2-A");
471+
472+
461473
}
462474

463475
TEST(headers_test, expect_test)

version.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
0.4.11.20241018
1+
0.4.12.20241028

0 commit comments

Comments
 (0)