How-to › Authenticate and authorize calls

How to pick an OAuth library, a hand-rolled flow, or a vendor SDK#

Choose the code that runs your OAuth login by swapping the issuer between a Keycloak and an Auth0 layout, and see which clients survive it and which tokens go stale.

Audience
API consumer
Level
beginner
Topic
Run OAuth 2.1 and OIDC flows
Languages
TypeScript, Go, Python, PHP and Ruby
Verified

Your company moves its users from Auth0 to Keycloak, and the login in your command-line tool stops at a 404. The client builds /authorize and /oauth/token from a domain name, and Keycloak serves those endpoints under /realms/<name>/protocol/openid-connect. The API client behind the login keeps a token in a field, so an hour later every call answers 401.

What you get

You will end up with a login that survives a change of identity provider, a generated API client that renews its token, and a test that swaps the issuer and proves both. This is for you if you are choosing the code that will run your OAuth flows.

Short answer

Run the login through a standards library such as oauth4webapi, which reads the issuer’s discovery document, so moving from Keycloak to Auth0 changes one URL. A hand-rolled flow over fetch survives too, if you write every check. A vendor SDK that pins its paths breaks on the other provider. Then give a generated SDK a token source, not a stored token: sdkgen through system.fetch, NSwag through transformOptions.

You will need

Node 22 or later and an OpenAPI 3 document whose security scheme is oauth2. You also need a public client registered at your identity provider with a loopback redirect URI, as RFC 8252 describes for native apps. The sample runs two stand-in issuers on 127.0.0.1. One follows the endpoint layout Keycloak documents, and one follows Auth0’s tenant layout. A third stand-in serves the Ledger API in api.json. The login is the authorization code grant with PKCE, RFC 7636, and the stand-ins accept only the S256 method.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
Auth0 SPA SDKAuth0 is your provider for the life of the productFixed /authorize and /oauth/token paths, so a change of provider is a rewrite of the loginYour provider may change, or you serve several
Hand-rolled fetch flowOne grant, no dependency budget, and you want to see every requestEvery check is yours: state, PKCE, issuer match, token errors, refresh rotationA certified library exists for your runtime
NSwagA TypeScript or C# API client, and the login is handled elsewhereIt ignores the oauth2 scheme, so the token arrives through a base class you writeYou want the scheme in the document to produce the auth code
oauth4webapiAny JavaScript runtime, any compliant issuer, login code you ownA low-level API: you assemble each step, and it refuses plain HTTP without an optionYou want sessions and middleware, as openid-client or a framework adds
sdkgenAn sdkgen client that should ask a token source before every attemptThe scheme becomes a Bearer prefix on a static apikey, so renewal needs system.fetch or a featureThe generator you use already runs the grant
Swagger CodegenA typescript-fetch client that reads the oauth2 scheme into an accessToken settingThe setting is a string or a synchronous function, so it cannot wait for a refreshTokens expire during the client’s lifetime and you do not wrap fetch

Voxgig maintains sdkgen. It is one of six options here, not the recommendation.

The library and the hand-rolled flow both read discovery, so both move between providers. The library costs one dependency with none of its own. The hand-rolled flow costs every check the library already makes. The Auth0 SPA SDK costs the provider change. Among the generated clients, NSwag’s async hook and sdkgen’s fetch seam can wait for a refresh, and Swagger Codegen’s token setting cannot.

Swap the issuer and run the same login

login.mjs runs the login three ways. The library version asks the issuer for its metadata, then builds every URL from what comes back. Nothing in it names a path.

export async function libraryLogin(issuer) {
  const issuerUrl = new URL(issuer)
  const as = await oauth.processDiscoveryResponse(
    issuerUrl,
    await oauth.discoveryRequest(issuerUrl, { algorithm: 'oidc', ...insecure }),
  )
  const verifier = oauth.generateRandomCodeVerifier()
  const state = oauth.generateRandomState()
  const url = new URL(as.authorization_endpoint)

insecure sets allowInsecureRequests, because the stand-ins speak HTTP on the loopback interface. A real issuer is HTTPS and needs no such option. The third version, pinnedLogin, builds its URLs from a domain and two fixed paths, as @auth0/auth0-spa-js 2.30.0 does in Auth0Client.ts and api.ts. That SDK runs in a browser, so the sample copies its URL scheme rather than running it.

node swap.mjs
keycloak-shaped issuer
  oauth4webapi       ok    2 invoices via /realms/ledger/protocol/openid-connect/token
  hand-rolled fetch  ok    2 invoices via /realms/ledger/protocol/openid-connect/token
  pinned paths       FAIL  authorization endpoint answered 404
auth0-shaped issuer
  oauth4webapi       ok    2 invoices via /oauth/token
  hand-rolled fetch  ok    2 invoices via /oauth/token
  pinned paths       ok    2 invoices via /oauth/token

Only the issuer URL changed between the two blocks. The pinned client works on the provider it was written for and fails on the first request to the other. Other languages have the same split: golang.org/x/oauth2 in Go, Authlib or requests-oauthlib in Python, league/oauth2-client in PHP and OmniAuth in Ruby, each with provider packages layered on top.

Hand the token to a generated client

sdkgen reads the document’s oauth2 scheme, and the generated configuration keeps one fact from it, the header prefix. The authorizationUrl and tokenUrl appear nowhere in the generated source.

        auth: {
            prefix: 'Bearer',
        },

The apikey option is sent as Bearer <apikey>, which suits a token that never expires. For one that does, the features reference documents options.system.fetch, a function every live request goes through. Pass one that asks a token source first:

export const authorizedFetch = (tokens) => async (url, init = {}) => {
  const headers = new Headers(init.headers)
  headers.set('authorization', `Bearer ${await tokens.getToken()}`)
  return fetch(url, { ...init, headers })
}

tokenSource in login.mjs returns the current access token, and exchanges the refresh token through oauth4webapi once it has expired. clients.mjs logs in once, calls, moves the clock past the sixty-second lifetime, and calls again.

node clients.mjs
client                    first call    after expiry  token requests
sdkgen apikey option      2 invoices    HTTP 401      1
sdkgen system.fetch       2 invoices    2 invoices    2
NSwag transformOptions    2 invoices    2 invoices    2
Swagger accessToken       2 invoices    HTTP 401      1
Swagger fetch argument    2 invoices    2 invoices    2

Two token requests means one code exchange and one refresh. sdkgen’s bundled secrets feature also exchanges a refresh token, but it posts to a path relative to the API’s base. That suits an API that issues its own tokens, not a separate identity provider.

Wire the token into NSwag and Swagger Codegen

NSwag generated nothing from the oauth2 scheme. Its TypeScript generator calls transformOptions on a base class before every request when UseTransformOptionsMethod is set, and the method returns a promise, so it can wait for a refresh. The base class goes in through /extensionCode:

export class AuthorizedClient {
  constructor(private tokens: TokenSource) {}

  // NSwag calls this before every request when UseTransformOptionsMethod is on.
  protected async transformOptions(options: RequestInit): Promise<RequestInit> {
    const token = await this.tokens.getToken()
    return { ...options, headers: { ...(options.headers as Record<string, string>), authorization: `Bearer ${token}` } }
  }
}

Swagger Codegen 3.0.85 does read the scheme. Its typescript-fetch output sets the header from configuration.accessToken, which may be a function, but a synchronous one:

            if (configuration && configuration.accessToken) {
                const localVarAccessTokenValue = typeof configuration.accessToken === 'function'
                    ? configuration.accessToken("ledgerAuth", ["invoices:read"])
                    : configuration.accessToken;
                localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue;
            }

That is the Swagger accessToken row in the output: the function returns the cached token, and the call after expiry is refused. The working substitute is the client’s third constructor argument, a fetch function, which takes the same authorizedFetch that sdkgen uses.

Check it worked

Eleven tests run against the stand-ins. One swaps the issuer for both discovery-driven logins, one expects the pinned client to fail on the Keycloak layout, and one checks each generated client’s result before and after expiry.

node --test oauth.test.mjs
1..11
# tests 11
# suites 0
# pass 11
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 597.773863

The others hold the stand-ins to the specifications. A wrong or malformed code_verifier is refused and spends the code, a request without code_challenge is sent back with invalid_request, and a rotated refresh token is refused on its second use. One more checks that authorizedFetch keeps the caller’s headers when they arrive as a Headers object.

When it goes wrong

Discovery fails with a message about the issuer. The URL you configured differs from the issuer in the metadata by a slash,1 and OpenID Connect Discovery requires the two to be identical. Copy the issuer from the metadata itself.

node pitfall.mjs
keycloak, issuer as published
  oauth4webapi       ok
  hand-rolled fetch  ok
keycloak, issuer with a slash added
  oauth4webapi       OperationProcessingError: "response" body "issuer" property does not match the expected value
  hand-rolled fetch  Error: discovery names issuer <origin>/realms/ledger
auth0, issuer as published
  oauth4webapi       ok
  hand-rolled fetch  ok
auth0, issuer with its slash dropped
  oauth4webapi       ok
  hand-rolled fetch  Error: discovery names issuer <origin>/

The last block differs because new URL gives a bare origin its slash back, and a string compare does not. A hand-rolled flow finds these differences one provider at a time.

The login reaches the provider and stops at a 404. The client pins its paths. Move to a client that reads authorization_endpoint and token_endpoint from discovery.

Calls succeed for an hour, then every one answers 401. The client holds a token, not a source of tokens. Give it a fetch function or hook that asks for the current token on every attempt.

When not to do this

Do not hand-roll the flow because the library looks large. oauth4webapi has no dependencies, and its README records an OpenID certification of its relying-party profiles.2 The checks in handRolledLogin are a subset of what it does.

Do not pick the Auth0 SPA SDK for a product whose identity provider is still being chosen. It is the shortest path on Auth0, and it pins you there.

Do not reach for sdkgen’s apikey option to carry an OAuth token that expires. Its scheme support stops at the Bearer prefix, so the token source is yours to write. NSwag is the better fit when the API client is all you need and your team builds with .NET. Its C# client is partial, with a PrepareRequest method that runs before each request, but that method returns void, so it cannot wait for a refresh the way transformOptions can. When your tokens outlive the process, Swagger Codegen’s accessToken setting is the least code of the three.

Do not store a refresh token where the browser’s scripts can read it; a single-page app has its own rules, set out in the OAuth security best current practice, RFC 9700.

Last verified

Verified 2026-11-21 against Node 22.23.5, oauth4webapi 3.8.9, @voxgig/create-sdkgen 0.31.9, @voxgig/sdkgen 4.44.3, NSwag 14.8.0 and Swagger Codegen 3.0.85. Every output block is what the command preceding it printed. All three generators were run once by generate.sh, and their compiled output is committed under generated/. sdkgen 4.45.0 generated identical source from the same document. The issuers are stand-ins, and Keycloak, Auth0 and the Auth0 SDK were not run.

Footnotes

  1. Auth0’s own SPA SDK appends the slash for you. Its utils.ts builds the expected token issuer as the domain URL followed by /. Given an issuer option without https://, it adds the scheme in front and the slash behind. Unless the option already starts with https://, the SDK checks each ID token’s issuer against the form with the slash. ↩︎ Back to text

  2. The oauth4webapi README states its dependency count in a heading that reads “Dependencies: 0” and says its author has certified it against the Basic, FAPI 1.0 and FAPI 2.0 relying-party profiles. Its sibling openid-client, the higher-level package by the same author, depends on oauth4webapi and on jose. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.