# 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.

Source: https://voxgig.com/howto/pick-an-oauth-client-library-or-hosted-sdk

- Audience: api-consumer
- Level: beginner
- Languages: typescript, go, python, php, ruby
- Verified: 2026-11-21
- Published: 2026-11-21

## 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](https://www.rfc-editor.org/rfc/rfc8252.html) describes for native apps. The sample
runs two stand-in issuers on `127.0.0.1`. One follows the endpoint layout
[Keycloak documents](https://www.keycloak.org/securing-apps/oidc-layers), 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](https://www.rfc-editor.org/rfc/rfc7636.html),
and the stand-ins accept only the `S256` method.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Auth0 SPA SDK](https://github.com/auth0/auth0-spa-js) | Auth0 is your provider for the life of the product | Fixed `/authorize` and `/oauth/token` paths, so a change of provider is a rewrite of the login | Your provider may change, or you serve several |
| [Hand-rolled fetch flow](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch) | One grant, no dependency budget, and you want to see every request | Every check is yours: state, PKCE, issuer match, token errors, refresh rotation | A certified library exists for your runtime |
| [NSwag](https://github.com/RicoSuter/NSwag/wiki/TypeScriptClientGenerator) | A TypeScript or C# API client, and the login is handled elsewhere | It ignores the `oauth2` scheme, so the token arrives through a base class you write | You want the scheme in the document to produce the auth code |
| [oauth4webapi](https://github.com/panva/oauth4webapi) | Any JavaScript runtime, any compliant issuer, login code you own | A low-level API: you assemble each step, and it refuses plain HTTP without an option | You want sessions and middleware, as openid-client or a framework adds |
| [sdkgen](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md) | An sdkgen client that should ask a token source before every attempt | The scheme becomes a `Bearer` prefix on a static `apikey`, so renewal needs `system.fetch` or a feature | The generator you use already runs the grant |
| [Swagger Codegen](https://swagger.io/docs/open-source-tools/swagger-codegen/codegen-v3/about/) | A `typescript-fetch` client that reads the `oauth2` scheme into an `accessToken` setting | The setting is a string or a synchronous function, so it cannot wait for a refresh | Tokens 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.

```js title="login.mjs"
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`](https://github.com/auth0/auth0-spa-js/blob/main/src/Auth0Client.ts) and
[`api.ts`](https://github.com/auth0/auth0-spa-js/blob/main/src/api.ts). That SDK runs in a
browser, so the sample copies its URL scheme rather than running it.

```bash
node swap.mjs
```

```text output
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`](https://pkg.go.dev/golang.org/x/oauth2) in Go,
[Authlib](https://docs.authlib.org/en/stable/oauth2/client/index.html) or
[requests-oauthlib](https://requests-oauthlib.readthedocs.io/en/latest/) in Python,
[league/oauth2-client](https://oauth2-client.thephpleague.com/) in PHP and
[OmniAuth](https://github.com/omniauth/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.

```js title="generated/sdkgen/Config.js"
        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](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md)
documents `options.system.fetch`, a function every live request goes through. Pass one that asks
a token source first:

```js title="clients.mjs"
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.

```bash
node clients.mjs
```

```text output
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`:

```ts title="nswag-extension.ts"
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:

```js title="generated/swagger-codegen/api.js"
            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.

```bash
node --test oauth.test.mjs
```

```text output
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](https://openid.net/specs/openid-connect-discovery-1_0.html) requires
the two to be identical. Copy the issuer from the metadata itself.

```bash
node pitfall.mjs
```

```text output
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.

## Related how-tos

- [Run authorization code with PKCE in a single-page app](/howto/pkce-in-a-single-page-app)

- [Run the client credentials flow inside a generated SDK](/howto/client-credentials-inside-a-generated-sdk)

- [Refresh an access token once under concurrent requests](/howto/refresh-a-token-once-under-concurrent-requests)

- [Diagnose a 401 or a 403 from a credential](/howto/diagnose-401-and-403-from-a-credential)

- [Hand a generated SDK its credential instead of a header](/howto/credential-options-in-a-generated-sdk)

## 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.

[^1]: Auth0's own SPA SDK appends the slash for you. Its
[`utils.ts`](https://github.com/auth0/auth0-spa-js/blob/main/src/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.

[^2]: The [oauth4webapi README](https://github.com/panva/oauth4webapi) states its dependency
count in a heading that reads "Dependencies: 0" and says its author has
[certified](https://openid.net/certification/) 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`.