From 5bfa38b34e7e9a8912c25f913765acd2c60e7957 Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Wed, 2 Dec 2026 22:21:35 +0000 Subject: [PATCH] Let the Anthropic client authenticate with a bearer token The Anthropic client always sent its credential in the `x-api-key` header, so it could only use an API key. The Anthropic API also takes an OAuth access token (what `ANTHROPIC_AUTH_TOKEN` holds for the official SDKs, and what `ant auth print-credentials --access-token` prints after `ant auth login`), and an LLM gateway in front of it usually takes a token of its own. Both go in `Authorization: Bearer `. Add `ai::anthropic::create_client_with_auth_token`, and an `AuthScheme` argument of `AnthropicClient` that selects the header. The `anthropic-version` header is sent in both cases. Nothing changes for an API key. Co-Authored-By: Claude Fable 5.2 --- include/ai/anthropic.h | 14 ++++ src/providers/anthropic/anthropic_client.cpp | 26 ++++++-- src/providers/anthropic/anthropic_client.h | 23 ++++++- src/providers/anthropic/anthropic_factory.cpp | 9 +++ src/providers/anthropic/anthropic_factory.h | 2 + tests/unit/anthropic_client_test.cpp | 65 +++++++++++++++++++ 6 files changed, 133 insertions(+), 6 deletions(-) diff --git a/include/ai/anthropic.h b/include/ai/anthropic.h index 0a10da7..a913903 100644 --- a/include/ai/anthropic.h +++ b/include/ai/anthropic.h @@ -67,6 +67,20 @@ Client create_client(const std::string& api_key, const std::string& base_url, const retry::RetryConfig& retry_config); +/// Create an Anthropic client that authenticates with a bearer token instead +/// of an API key. The token is sent as `Authorization: Bearer `: this is +/// how the Anthropic API takes an OAuth access token (what the +/// `ANTHROPIC_AUTH_TOKEN` environment variable of the official SDKs holds), and +/// how an LLM gateway in front of it usually takes a token of its own. An API +/// key is not accepted this way: use `create_client` for it. +/// @param auth_token Bearer token; must not be empty (there is no fallback to +/// an environment variable) +/// @param base_url Custom base URL; the default one when empty +/// @return Configured Anthropic client +/// @throws ConfigurationError if the token is empty +Client create_client_with_auth_token(const std::string& auth_token, + const std::string& base_url = ""); + /// Try to create an Anthropic client using environment variables /// Reads API key from ANTHROPIC_API_KEY environment variable /// @return Optional client - has value if environment variable is set, empty diff --git a/src/providers/anthropic/anthropic_client.cpp b/src/providers/anthropic/anthropic_client.cpp index 4516235..b051810 100644 --- a/src/providers/anthropic/anthropic_client.cpp +++ b/src/providers/anthropic/anthropic_client.cpp @@ -14,26 +14,42 @@ namespace anthropic { AnthropicClient::AnthropicClient(const std::string& api_key, const std::string& base_url) - : AnthropicClient(api_key, base_url, std::optional{}) {} + : AnthropicClient(api_key, + base_url, + AuthScheme::kApiKey, + std::optional{}) {} AnthropicClient::AnthropicClient(const std::string& api_key, const std::string& base_url, const retry::RetryConfig& retry_config) : AnthropicClient(api_key, base_url, + AuthScheme::kApiKey, std::optional(retry_config)) {} -AnthropicClient::AnthropicClient(const std::string& api_key, +AnthropicClient::AnthropicClient(const std::string& credential, + const std::string& base_url, + AuthScheme auth_scheme) + : AnthropicClient(credential, + base_url, + auth_scheme, + std::optional{}) {} + +AnthropicClient::AnthropicClient(const std::string& credential, const std::string& base_url, + AuthScheme auth_scheme, std::optional retry_config) : BaseProviderClient( providers::ProviderConfig{ - .api_key = api_key, + .api_key = credential, .base_url = base_url, .completions_endpoint_path = "/v1/messages", .embeddings_endpoint_path = "/v1/embeddings", - .auth_header_name = "x-api-key", - .auth_header_prefix = "", + .auth_header_name = auth_scheme == AuthScheme::kBearerToken + ? "Authorization" + : "x-api-key", + .auth_header_prefix = + auth_scheme == AuthScheme::kBearerToken ? "Bearer " : "", .extra_headers = {{"anthropic-version", "2023-06-01"}}, .retry_config = retry_config}, std::make_unique(), diff --git a/src/providers/anthropic/anthropic_client.h b/src/providers/anthropic/anthropic_client.h index 509f861..fd9be72 100644 --- a/src/providers/anthropic/anthropic_client.h +++ b/src/providers/anthropic/anthropic_client.h @@ -11,6 +11,15 @@ namespace ai { namespace anthropic { +/// How the client presents its credential to the API. +enum class AuthScheme { + /// An API key, sent in the `x-api-key` header. + kApiKey, + /// A bearer token, sent as `Authorization: Bearer `: an OAuth access + /// token of the Anthropic API, or the token of an LLM gateway. + kBearerToken, +}; + class AnthropicClient : public providers::BaseProviderClient { public: explicit AnthropicClient( @@ -21,6 +30,11 @@ class AnthropicClient : public providers::BaseProviderClient { const std::string& base_url, const retry::RetryConfig& retry_config); + /// `credential` is an API key or a bearer token, as `auth_scheme` says. + AnthropicClient(const std::string& credential, + const std::string& base_url, + AuthScheme auth_scheme); + // Override only what's specific to Anthropic StreamResult stream_text(const StreamOptions& options) override; std::string provider_name() const override; @@ -32,10 +46,17 @@ class AnthropicClient : public providers::BaseProviderClient { // Member access for testing const std::string& get_api_key() const { return config_.api_key; } const std::string& get_base_url() const { return config_.base_url; } + const std::string& get_auth_header_name() const { + return config_.auth_header_name; + } + const std::string& get_auth_header_prefix() const { + return config_.auth_header_prefix; + } private: - AnthropicClient(const std::string& api_key, + AnthropicClient(const std::string& credential, const std::string& base_url, + AuthScheme auth_scheme, std::optional retry_config); }; diff --git a/src/providers/anthropic/anthropic_factory.cpp b/src/providers/anthropic/anthropic_factory.cpp index 4c358b0..b00e992 100644 --- a/src/providers/anthropic/anthropic_factory.cpp +++ b/src/providers/anthropic/anthropic_factory.cpp @@ -55,6 +55,15 @@ Client create_client(const std::string& api_key, retry_config)); } +Client create_client_with_auth_token(const std::string& auth_token, + const std::string& base_url) { + if (auth_token.empty()) { + throw ConfigurationError("The auth token of the Anthropic client is empty"); + } + return Client(std::make_unique( + auth_token, get_base_url_or_default(base_url), AuthScheme::kBearerToken)); +} + std::optional try_create_client() { auto api_key = utils::non_empty_env("ANTHROPIC_API_KEY"); if (!api_key) { diff --git a/src/providers/anthropic/anthropic_factory.h b/src/providers/anthropic/anthropic_factory.h index 8be594e..fa11e59 100644 --- a/src/providers/anthropic/anthropic_factory.h +++ b/src/providers/anthropic/anthropic_factory.h @@ -10,6 +10,8 @@ namespace anthropic { Client create_client(); Client create_client(const std::string& api_key); Client create_client(const std::string& api_key, const std::string& base_url); +Client create_client_with_auth_token(const std::string& auth_token, + const std::string& base_url); } // namespace anthropic } // namespace ai \ No newline at end of file diff --git a/tests/unit/anthropic_client_test.cpp b/tests/unit/anthropic_client_test.cpp index aeab3da..22936ca 100644 --- a/tests/unit/anthropic_client_test.cpp +++ b/tests/unit/anthropic_client_test.cpp @@ -3,6 +3,7 @@ // Include the Anthropic client headers #include "ai/anthropic.h" +#include "ai/errors.h" #include "ai/types/generate_options.h" #include "ai/types/stream_options.h" @@ -90,6 +91,70 @@ TEST_F(AnthropicClientTest, ConstructorWithCustomRetryConfig) { EXPECT_EQ(client.get_base_url(), "https://api.anthropic.com"); } +// Authentication Scheme Tests +TEST_F(AnthropicClientTest, ApiKeyIsSentInXApiKeyHeader) { + ai::anthropic::AnthropicClient client("sk-ant-test", + "https://api.anthropic.com"); + + EXPECT_EQ(client.get_auth_header_name(), "x-api-key"); + EXPECT_EQ(client.get_auth_header_prefix(), ""); + + ai::anthropic::AnthropicClient explicit_client( + "sk-ant-test", "https://api.anthropic.com", + ai::anthropic::AuthScheme::kApiKey); + + EXPECT_EQ(explicit_client.get_auth_header_name(), "x-api-key"); + EXPECT_EQ(explicit_client.get_auth_header_prefix(), ""); +} + +TEST_F(AnthropicClientTest, AuthTokenIsSentAsBearer) { + ai::anthropic::AnthropicClient client( + "token-123", "https://api.anthropic.com", + ai::anthropic::AuthScheme::kBearerToken); + + EXPECT_TRUE(client.is_valid()); + EXPECT_EQ(client.get_api_key(), "token-123"); + EXPECT_EQ(client.get_base_url(), "https://api.anthropic.com"); + EXPECT_EQ(client.get_auth_header_name(), "Authorization"); + EXPECT_EQ(client.get_auth_header_prefix(), "Bearer "); +} + +TEST_F(AnthropicClientTest, BearerTokenHeadersKeepTheApiVersion) { + // The headers of a request are built from the configuration of the client: + // with a bearer token there is an `Authorization` header and no `x-api-key`. + providers::ProviderConfig config; + config.api_key = "token-123"; + config.auth_header_name = "Authorization"; + config.auth_header_prefix = "Bearer "; + config.extra_headers = {{"anthropic-version", "2023-06-01"}}; + + ai::anthropic::AnthropicRequestBuilder builder; + auto headers = builder.build_headers(config); + + ASSERT_EQ(headers.count("Authorization"), 1U); + EXPECT_EQ(headers.find("Authorization")->second, "Bearer token-123"); + EXPECT_EQ(headers.count("x-api-key"), 0U); + ASSERT_EQ(headers.count("anthropic-version"), 1U); + EXPECT_EQ(headers.find("anthropic-version")->second, "2023-06-01"); +} + +TEST_F(AnthropicClientTest, CreateClientWithAuthToken) { + auto client = ai::anthropic::create_client_with_auth_token( + "token-123", "http://localhost:8080"); + + EXPECT_TRUE(client.is_valid()); + EXPECT_EQ(client.provider_name(), "anthropic"); + + auto default_url_client = + ai::anthropic::create_client_with_auth_token("token-123"); + EXPECT_THAT(default_url_client.config_info(), + testing::HasSubstr("https://api.anthropic.com")); + + // No fallback to an environment variable: an empty token is an error. + EXPECT_THROW(ai::anthropic::create_client_with_auth_token(""), + ai::ConfigurationError); +} + // Model Support Tests TEST_F(AnthropicClientTest, SupportedModelsContainsExpectedModels) { auto models = client_->supported_models();