# Token Authentication (/sdks/cpp/how-to/connection/token-auth)



## Overview [#overview]

**Token authentication** proves a client's identity to a KubeMQ server that has authentication enabled, without embedding a username/password or issuing per-client TLS certs. It's the mechanism you reach for in shared clusters, multi-tenant deployments, or any environment where you need to control and audit which clients are allowed to connect — the token is issued and revoked by your identity provider, not baked into the binary.

The token travels as a raw `authorization` gRPC metadata value (no `Bearer ` prefix added) attached to every outgoing call, set via `options.set_auth_token(token)` before the client is created. The server validates it before honoring any RPC, including the initial handshake. Because a static token eventually expires, `options.set_credential_provider(provider)` accepts a `StaticTokenProvider` or a custom `CredentialProvider` implementation, and the SDK refreshes the token automatically instead of requiring the client to be rebuilt.

**Gotchas:** an invalid or expired token isn't rejected until the first real RPC — call `Ping()` right after `Client::Create(options)` so failures surface immediately instead of on your first business request, and always check `ok()` on the returned `StatusOr` before dereferencing; never hardcode a real token, read it from an environment variable such as `KUBEMQ_AUTH_TOKEN` or a secrets manager; and a plain `set_auth_token` value never refreshes itself, so short-lived JWTs need a `CredentialProvider`, not a periodically-restarted client.

## Prerequisites [#prerequisites]

* KubeMQ server running on `localhost:50000`
* C++ SDK installed (vcpkg or CMake FetchContent)
* C++17 compiler (GCC 9+, Clang 9+, MSVC 2019+)
* KubeMQ server configured for token authentication

## Code [#code]

```cpp title="main.cc"
// Example: connection/token_auth
//
// Demonstrates connecting to a KubeMQ server with JWT/token authentication.
// The auth token is set on the client options and included in every gRPC request.
//
// Channel: cpp-connection.token-auth
// Client ID: cpp-connection-token-auth-client
//
// Run with a KubeMQ server configured for token authentication.

#include <kubemq/kubemq.h>

#include <cstdlib>
#include <iostream>

int main() {
    // Read auth token from environment or use a placeholder
    const char* env_token = std::getenv("KUBEMQ_AUTH_TOKEN");
    std::string token = env_token ? env_token : "your-auth-token-here";

    std::cout << "[1] Connecting with auth token to localhost:50000" << std::endl;

    kubemq::ClientOptions options;
    options.set_address("localhost", 50000);
    options.set_client_id("cpp-connection-token-auth-client");
    options.set_auth_token(token);

    auto client_result = kubemq::Client::Create(options);
    if (!client_result.ok()) {
        std::cerr << "[ERROR] Failed to create client: " << client_result.status().message()
                  << std::endl;
        return 1;
    }
    auto& client = *client_result;

    auto ping_result = client->Ping();
    if (!ping_result.ok()) {
        std::cerr << "[ERROR] Ping failed: " << ping_result.status().message() << std::endl;
        return 1;
    }
    std::cout << "[2] Connected with auth token. Server version: " << ping_result->version
              << std::endl;

    auto close_status = client->Close();
    if (!close_status.ok()) {
        std::cerr << "[ERROR] Close failed: " << close_status.message() << std::endl;
        return 1;
    }
    std::cout << "[3] Client closed" << std::endl;

    return 0;
}
```

## How It Works [#how-it-works]

* Reads the auth token from the `KUBEMQ_AUTH_TOKEN` environment variable (falls back to a placeholder string for development).
* Calls `options.set_auth_token(token)` — the SDK injects the token as a raw `authorization` gRPC metadata key on every outgoing call. No `Bearer ` prefix is added; the value is sent exactly as provided.
* Creates the client with `Client::Create(options)`, which returns a `StatusOr<unique_ptr<Client>>` — always check `ok()` before dereferencing.
* Verifies the authenticated connection with `Ping()`, which returns server metadata including the version string.
* For dynamic token refresh (e.g., rotating secrets or short-lived JWTs), use `options.set_credential_provider(provider)` with a `StaticTokenProvider` or a custom `CredentialProvider` implementation instead.

## Related [#related]

* [C++ SDK Reference](/sdks/cpp/reference/client)
* [Connect](/sdks/cpp/tutorials/connect)
* [TLS Setup](/sdks/cpp/how-to/tls/tls-setup)
