Skip to content

Commit

Permalink
Feat: Add method to extract HTTP Bearer token from Authorization header.
Browse files Browse the repository at this point in the history
  • Loading branch information
mowijo committed Oct 28, 2024
1 parent 2d573ad commit 0371816
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 1 deletion.
4 changes: 4 additions & 0 deletions include/pistache/http_header.h
Original file line number Diff line number Diff line change
Expand Up @@ -479,11 +479,15 @@ namespace Pistache::Http::Header
// Get decoded user ID and password if basic method was used...
std::string getBasicUser() const;
std::string getBasicPassword() const;
std::string getBearerToken() const;

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


void setBearertoken(const std::string& token);

void parse(const std::string& data) override;
void write(std::ostream& os) const override;

Expand Down
10 changes: 10 additions & 0 deletions src/common/http_header.cc
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,16 @@ namespace Pistache::Http::Header
return true;
}

std::string Authorization::getBearerToken() const
{
// Verify bearer authorization method was used...
if (!hasMethod<Authorization::Method::Bearer>())
throw std::runtime_error("Authorization header does not use Bearer method.");

const std::string token(value_.begin() + std::string("Bearer ").length(), value_.end());
return token;
}

// Get decoded user ID if basic method was used...
std::string Authorization::getBasicUser() const
{
Expand Down
12 changes: 12 additions & 0 deletions tests/headers_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,7 @@ TEST(headers_test, authorization_basic_test)
// Verify it decoded correctly...
ASSERT_EQ(au.getBasicUser(), "Aladdin");
ASSERT_EQ(au.getBasicPassword(), "OpenSesame");
EXPECT_ANY_THROW( au.getBearerToken() );
}

TEST(headers_test, authorization_bearer_test)
Expand Down Expand Up @@ -458,6 +459,17 @@ TEST(headers_test, authorization_bearer_test)
"eyJleHAiOjE1NzA2MzA0MDcsImlhdCI6MTU3MDU0NDAwNywibmFtZSI6IkFkbWluIE5hbWUi"
"LCJzYW1wbGUiOiJUZXN0In0.zLTAAnBftlqccsU-4mL69P4tQl3VhcglMg-"
"d0131JxqX4xSZLlO5xMRrCPBgn_00OxKJ9CQdnpjpuzblNQd2-A");

EXPECT_ANY_THROW(au.getBasicUser() );
EXPECT_ANY_THROW(au.getBasicPassword() );

ASSERT_EQ(au.getBearerToken(),
"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXUyJ9."
"eyJleHAiOjE1NzA2MzA0MDcsImlhdCI6MTU3MDU0NDAwNywibmFtZSI6IkFkbWluIE5hbWUi"
"LCJzYW1wbGUiOiJUZXN0In0.zLTAAnBftlqccsU-4mL69P4tQl3VhcglMg-"
"d0131JxqX4xSZLlO5xMRrCPBgn_00OxKJ9CQdnpjpuzblNQd2-A");


}

TEST(headers_test, expect_test)
Expand Down
2 changes: 1 addition & 1 deletion version.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.4.11.20241018
0.4.12.20241028

0 comments on commit 0371816

Please sign in to comment.