TokenBroker

Home / Setup Guide / Adding a Provider

Setup Guide: Adding a Provider

How to teach TokenBroker a new service, using Zoho (already live) as the reference. Budget about half an hour: ten minutes of provider console and vault work, ten of code, ten of deploy and testing.

Everything follows one convention set, so a new provider looks like every existing one:

Convention Example (Zoho)
Provider key (lowercase) zoho
Vault secrets zoho-client-id, zoho-client-secret, zoho-refresh-token
Local fallback settings ZohoClientId, ZohoClientSecret, ZohoRefreshToken
Token provider class Providers/Zoho/ZohoTokenProvider.cs
Functions class Providers/Zoho/ZohoMailFunctions.cs
Routes /api/zoho/mail/... (namespaced by provider key)
Wiki page Token Setup /

Part 1: Register a dedicated OAuth client

In the provider's developer console, create a client for TokenBroker alone. Never reuse a client that belongs to another tool.

Note down:

Part 2: Client id and secret into the vault

Azure portal, your vault, Objects, Secrets, Generate/Import, manual: create <provider>-client-id and <provider>-client-secret. The account owner types the secret in the portal. It never goes in chat, in code, or in this repo.

Part 3: The token provider class

One small class: configuration over the shared OAuthTokenService base, which owns the cache, the serialized refresh, the grant POST, and the rotation write-back.

using Microsoft.Extensions.Logging;
using TokenBroker.Secrets;

namespace TokenBroker.Providers.Example;

public sealed class ExampleTokenProvider : OAuthTokenService
{
    public const string HttpClientName = "example";

    public ExampleTokenProvider(IHttpClientFactory httpClientFactory,
        ISecretStore secrets, ILogger<ExampleTokenProvider> logger)
        : base(new OAuthProviderOptions(
            Name: "example",
            TokenEndpoint: "https://login.example.com/oauth/v2/token",
            SecretPrefix: "example",
            HttpClientName: HttpClientName,
            AuthStyle: ClientAuthStyle.FormSecret,   // or Basic
            RotatesRefreshToken: false),             // true if it rotates
          httpClientFactory, secrets, logger)
    {
    }

    // Only for providers with a non-Bearer scheme. Delete if Bearer.
    public override string AuthorizationHeaderValue(string accessToken)
        => $"Example-oauthtoken {accessToken}";
}

Part 4: The functions class

A thin class holding only the provider's route shapes and parameters. Token handling and forwarding are the base class and ProviderProxy.

using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using TokenBroker.Proxy;

namespace TokenBroker.Providers.Example;

public sealed class ExampleFunctions
{
    private readonly ExampleTokenProvider _provider;
    private readonly ProviderProxy _proxy;
    private readonly ILogger<ExampleFunctions> _logger;

    public ExampleFunctions(ExampleTokenProvider provider, ProviderProxy proxy,
        ILogger<ExampleFunctions> logger)
    {
        _provider = provider;
        _proxy = proxy;
        _logger = logger;
    }

    private Task<HttpResponseData> ProxyAsync(HttpRequestData req,
        HttpMethod method, string path, string? jsonBody) =>
        _proxy.ForwardAsync(req, _provider, ExampleTokenProvider.HttpClientName,
            "https://api.example.com", method, path, jsonBody, _logger);

    [Function("ExamplePing")]
    public Task<HttpResponseData> Ping(
        [HttpTrigger(AuthorizationLevel.Function, "get",
            Route = "example/ping")] HttpRequestData req) =>
        ProxyAsync(req, HttpMethod.Get, "/v1/ping", null);
}

Pick one trivial read route first (an accounts or profile call is ideal); it becomes your end-to-end test.

Part 5: Register it

In Program.cs, one block per provider:

services.AddHttpClient(ExampleTokenProvider.HttpClientName);
services.AddSingleton<ExampleTokenProvider>();
services.AddSingleton<ITokenProvider>(
    sp => sp.GetRequiredService<ExampleTokenProvider>());

Add the provider's base URLs to appsettings.json under Providers:<Name>:... if your functions read them from configuration (Zoho does: Providers:Zoho:AccountsBase, Providers:Zoho:MailBase).

Part 6: Build, deploy, sanity-check

dotnet build -c Release   # must be 0 warnings, 0 errors
func azure functionapp publish <app> --dotnet-isolated

Confirm the new functions appear in az functionapp function list, and that calling the new route without the function key returns 401.

Part 7: The bootstrap ceremony (one time)

The refresh token is minted once, by hand, because grant codes are single-use and expire in minutes. Have the exchange ready before you generate the code.

  1. In the provider's console (Zoho: the Self Client's Generate Code tab), generate an authorization code for exactly the scopes from Part 1, longest duration offered.
  2. Immediately exchange it for tokens. A small exchange script kept with the operator's tooling (the Zoho bootstrap used one) is the model: it reads the client id and secret from the vault, POSTs grant_type=authorization_code to the token endpoint, and stores the returned refresh token as <provider>-refresh-token. It prints no token values, only lengths and status codes.
  3. Verify the vault now holds all three secrets: az keyvault secret list --vault-name <vault>.

Two hard-won warnings:

Some providers use a browser redirect flow instead of a self-client code generator. The ceremony is the same shape: capture the code from the redirect, exchange it immediately, store the refresh token.

Part 8: Test end to end

Call your Part 4 test route with the function key:

curl -H "x-functions-key: <key>" https://<app>.azurewebsites.net/api/example/ping

Success means the whole chain worked: vault read by managed identity, refresh grant accepted, API call authorized, provider JSON returned. Record the date, route, and result on the provider's wiki page, and add a real route or two (search, read, send) following the Zoho functions as the pattern.

Part 9: Write the provider's wiki page

Add Token Setup / <Provider> next to the Zoho page, with: the client type and where it was registered, the exact scope list, vault secret names, token limits, the endpoints table, the verification record, and provider-specific troubleshooting. Future-you, debugging a 401 at midnight, is the audience.