@hapic/oauth2
v4.3.1
Published
An OAuth2 and OpenID Connect client: authorize URLs, token grants, device authorization, introspection, revocation and userinfo.
Maintainers
Readme
Why @hapic/oauth2?
Talking to an OAuth2 server with plain fetch means the same chores in every project: encode an authorize URL, post a form-encoded body per grant, decide whether the client id and secret go into the body or into a Basic header, keep an app-wide bearer token out of the token request, and copy endpoint URLs out of the provider's discovery document. Each of these is easy to get slightly wrong, and some mistakes leak secrets.
@hapic/oauth2 does that work on top of the hapic client:
| Concern | Without it | With @hapic/oauth2 |
|---|---|---|
| Authorize URL | You concatenate and encode the query yourself; a shared parameters object can put client_secret or code_verifier into a URL the browser keeps in its history. | authorize.buildURL() takes typed OAuth2, PKCE and OpenID Connect parameters, fills client_id, redirect_uri and scope from the client options, and never writes token request credentials to the URL. |
| Token grants | One URLSearchParams body per grant, Content-Type set by hand, the client credentials added to each call. | One method per grant (createWithClientCredentials, createWithPassword, createWithAuthorizationCode, createWithRefreshToken, createWithDeviceCode, createWithRobotCredentials, createWithTokenExchange) that sends a form body with the configured credentials, and pollWithDeviceCode for the device flow (RFC 8628). |
| Client authentication | You pick body or Basic header per provider and implement both. | Body by default; clientCredentialsAsHeader: true moves the id and secret to a Basic header and out of the body. |
| Stray authorization header | A bearer token set on your HTTP client for API calls is also sent to the token endpoint. | Token, introspection, revocation and device authorization requests drop the client's Authorization header unless you opt in with authorizationHeaderInherit. |
| Endpoints | You copy URLs from the provider's documentation or parse .well-known/openid-configuration yourself. | createClientWithOpenIDDiscoveryURL() fetches the metadata and returns a configured client. |
| Failures | You check response.ok and parse the error body. | A 4xx/5xx rejects with an HttpResponseError that carries the response; guards such as isClientErrorWithStatusCode are exported. |
The same client credentials grant, twice:
// with fetch
const response = await fetch('https://auth.example.com/oauth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: 'my-app',
client_secret: 'secret',
scope: 'api:read',
}),
});
if (!response.ok) {
throw new Error(`token request failed: ${response.status}`);
}
const token = await response.json();// with @hapic/oauth2
import { OAuth2Client } from '@hapic/oauth2';
const client = new OAuth2Client({
options: {
tokenEndpoint: 'https://auth.example.com/oauth/token',
clientId: 'my-app',
clientSecret: 'secret',
scope: 'api:read',
},
});
const token = await client.token.createWithClientCredentials();
// { access_token: '…', expires_in: 3600, token_type: 'Bearer' }Table of Contents
- Installation
- Configuration
- Authorization URL
- Token grants
- Client authentication
- Refresh, introspect and revoke
- Device authorization
- Userinfo
- OpenID Connect discovery
- Instances
- Errors
- API
- Notes
- Contributing
- License
Installation
npm install @hapic/oauth2 hapic --save- ESM only (
import), with type declarations. There is no CommonJS build. - Node.js
>=22.0.0. It also runs in browsers and workers, because requests go throughfetch. hapicis a peer dependency: install it next to this package.OAuth2Clientextends itsClient, so hooks, headers, transports and thetimeoutoption work as described in the hapic guide.
Configuration
OAuth2Client takes a request block, the options of the base hapic client, and an options block with your client registration and the provider's endpoints.
import { OAuth2Client } from '@hapic/oauth2';
const client = new OAuth2Client({
request: {
baseURL: 'https://auth.example.com/',
timeout: 10_000,
},
options: {
clientId: 'my-app',
clientSecret: 'secret',
redirectUri: 'https://app.example.com/callback',
scope: ['openid', 'profile', 'email'],
authorizationEndpoint: 'https://auth.example.com/oauth/authorize',
tokenEndpoint: '/oauth/token',
userinfoEndpoint: '/oauth/userinfo',
},
});| Option | Type | Default | Used for |
|---|---|---|---|
| clientId | string | | client_id of the authorize URL and of token requests |
| clientSecret | string | | client_secret of token requests (body, or Basic header with clientCredentialsAsHeader) |
| redirectUri | string | | redirect_uri of the authorize URL and of the authorization code grant |
| scope | string \| string[] | | scope of the authorize URL, of the device authorization request and of the client credentials, password and refresh token grants |
| realmId | string | | Sent as realm_id in the body of token.create* and deviceAuthorization.create requests (a non-standard parameter for servers with realms) |
| authorizationEndpoint | string | authorize, resolved against baseURL | authorize.buildURL(). Must be an absolute URL |
| tokenEndpoint | string | /token | token.create* |
| introspectionEndpoint | string | /token/introspect | token.introspect |
| revocationEndpoint | string | /token/revoke | token.revoke |
| userinfoEndpoint | string | /userinfo | userInfo.get |
| deviceAuthorizationEndpoint | string | /device_authorization | deviceAuthorization.create |
- The token, introspection, revocation, userinfo and device authorization endpoints may be absolute or relative. A relative one is appended to
baseURL, path included:/tokenwithbaseURL: 'https://auth.example.com/api/'becomeshttps://auth.example.com/api/token. - The authorization endpoint is different, because the URL is built rather than requested: set
authorizationEndpointto an absolute URL. Without it,authorizeis resolved againstbaseURLlike a link, sohttps://auth.example.com/api/gives…/api/authorizebuthttps://auth.example.com/apigives…/authorize. A relativeauthorizationEndpoint, or neither option, makesbuildURL()throw aTypeError(Invalid URL). client.optionsis one object shared byclient.authorize,client.token,client.userInfoandclient.deviceAuthorization. Changing a property later (client.options.clientId = 'other') affects all of them.
Authorization URL
authorize.buildURL() returns the URL you redirect the browser to. It fills client_id, redirect_uri and scope from the client options when you leave them out and sets response_type=code by default.
import { createHash, randomBytes } from 'node:crypto';
// PKCE: you create the verifier and its challenge, the client only transports them
const codeVerifier = randomBytes(32).toString('base64url');
const codeChallenge = createHash('sha256').update(codeVerifier).digest('base64url');
const url = client.authorize.buildURL({
state: 'af0ifjsldkj',
code_challenge: codeChallenge,
code_challenge_method: 'S256',
nonce: 'n-0S6_WzA2Mj',
prompt: ['login', 'consent'],
max_age: 0,
audience: 'https://api.example.com',
});
// https://auth.example.com/oauth/authorize?response_type=code&client_id=my-app
// &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback&scope=openid+profile+email
// &state=af0ifjsldkj&code_challenge=…&code_challenge_method=S256&nonce=n-0S6_WzA2Mj
// &prompt=login+consent&max_age=0&audience=https%3A%2F%2Fapi.example.comTyped parameters (AuthorizeParameters):
| Parameter | Type | Source |
|---|---|---|
| response_type | 'code' \| 'token' \| 'id_token' \| 'none', or an array of them | OAuth2; default code |
| client_id, redirect_uri | string | OAuth2; default options.clientId, options.redirectUri |
| scope | string \| string[] | OAuth2; default options.scope |
| state | string | OAuth2 |
| response_mode | 'query' \| 'fragment' \| 'form_post' \| 'web_message' | OAuth2 response modes |
| code_challenge, code_challenge_method | string, 'S256' \| 'plain' | PKCE (RFC 7636) |
| nonce, id_token_hint, login_hint | string | OpenID Connect |
| display | 'page' \| 'popup' \| 'touch' \| 'wap' | OpenID Connect |
| prompt | 'none' \| 'login' \| 'consent' \| 'select_account', or an array of them | OpenID Connect |
| max_age | number \| string | OpenID Connect, seconds |
| ui_locales, acr_values | string \| string[] | OpenID Connect |
The enums AuthorizeResponseType, AuthorizeResponseMode, AuthorizeCodeChallengeMethod, AuthorizeDisplay and AuthorizePrompt hold the same values.
Rules:
- Typed parameters are written first, in a fixed order. An array is joined with spaces (duplicates removed), a number is turned into a string, and an empty value (
'',null,undefined, an empty array) is left out. - Any other key is a custom parameter (
audience,resource, a provider extension) and is appended after the typed ones in input order. An array repeats the parameter once per item, soresource: ['https://a.example.com', 'https://b.example.com']gives tworesourceparameters (RFC 8707). - A custom parameter replaces a parameter of the same name the endpoint URL already carries:
authorizationEndpoint: 'https://auth.example.com/authorize?audience=default'withaudience: 'api'ends with oneaudience=api. - Credentials are never written:
client_secret,client_assertion,code_verifier,passwordandrefresh_tokenare dropped even when the object carries them, because the browser keeps the URL in its address bar and history and it can end up in referrers and server logs. Pass a dedicated object tobuildURL()anyway; the token methods add the client secret to the object you give them (see Notes). buildAuthorizeURL(endpoint, parameters)is the same function without a client: it applies the same rules and theresponse_type=codedefault, but does not read client options.endpointmust be an absolute URL.
import { buildAuthorizeURL } from '@hapic/oauth2';
const url = buildAuthorizeURL('https://auth.example.com/oauth/authorize', {
client_id: 'my-app',
redirect_uri: 'https://app.example.com/callback',
resource: ['https://a.example.com', 'https://b.example.com'],
});Token grants
Each grant has a method that posts a form-encoded body to tokenEndpoint and resolves with a TokenGrantResponse.
// service to service
let token = await client.token.createWithClientCredentials({ scope: 'api:read' });
// resource owner password
token = await client.token.createWithPassword({
username: 'admin',
password: 'start123',
});
// authorization code, in the callback handler (PKCE: pass the verifier from above)
token = await client.token.createWithAuthorizationCode({
code: 'SplxlOBeZQQYbYS6WxSbIA',
code_verifier: codeVerifier,
});
// refresh
token = await client.token.createWithRefreshToken({
refresh_token: 'tGzv3JOkF0XG5Qx2TlKWIA',
});
// robot credentials (grant_type=robot_credentials, non-standard)
token = await client.token.createWithRobotCredentials({
id: 'system',
secret: 'start123',
});
// token exchange (RFC 8693), see below
token = await client.token.createWithTokenExchange({
subject_token: token.access_token,
subject_token_type: TokenTypeIdentifier.ACCESS_TOKEN,
audience: 'https://api.example.com',
});
console.log(token);
// { access_token: '…', expires_in: 3600, token_type: 'Bearer', refresh_token: '…' }| Method | grant_type | Parameters | Filled from the options when missing |
|---|---|---|---|
| createWithClientCredentials(parameters?) | client_credentials | scope? | scope, client_id, client_secret, realm_id |
| createWithPassword(parameters) | password | username, password, scope? | scope, client_id, client_secret, realm_id |
| createWithAuthorizationCode(parameters) | authorization_code | code, code_verifier?, redirect_uri? | redirect_uri, client_id, client_secret, realm_id |
| createWithRefreshToken(parameters) | refresh_token | refresh_token, scope? | scope, client_id, client_secret, realm_id |
| createWithDeviceCode(parameters) | urn:ietf:params:oauth:grant-type:device_code | device_code | client_id, client_secret, realm_id |
| createWithRobotCredentials(parameters) | robot_credentials | id, secret | client_id, client_secret, realm_id |
| createWithTokenExchange(parameters) | urn:ietf:params:oauth:grant-type:token-exchange | subject_token, subject_token_type, actor_token? with actor_token_type, requested_token_type?, audience?, resource?, scope?, extension parameters | client_id, client_secret, realm_id |
| create(parameters) | from parameters.grant_type | any of the above, with grant_type | as for that grant |
- Every method also accepts
client_id,client_secretandrealm_idin the parameters. When you passclient_id, the configured id and secret are not added to the body; aclient_secretwithout aclient_idis replaced by the configured pair. - String values are written to the body, numbers and booleans are stringified, arrays are joined with spaces (
scope: ['a', 'b']givesscope=a b), and empty values or values of other types are left out.audienceandresourcearrays repeat the parameter once per item instead (audience=a&audience=b, RFC 8693, RFC 8707). - The response keeps
access_token,expires_in,token_type(Bearerwhen the server sends none) and, when present,refresh_token,refresh_token_expires_in,id_token,mac_key,mac_algorithmandissued_token_type(RFC 8693). Every other field, includingscope, is dropped.
Token exchange
createWithTokenExchange (RFC 8693) trades a token for another one, e.g. a user's access token for a token of another audience. TokenTypeIdentifier holds the token type URIs (ACCESS_TOKEN, REFRESH_TOKEN, ID_TOKEN, SAML1, SAML2, JWT).
import { TokenTypeIdentifier } from '@hapic/oauth2';
const token = await client.token.createWithTokenExchange({
subject_token: userToken,
subject_token_type: TokenTypeIdentifier.ACCESS_TOKEN,
actor_token: serviceToken,
actor_token_type: TokenTypeIdentifier.ACCESS_TOKEN,
audience: ['api-a', 'api-b'],
// parameters of the authorization server beyond RFC 8693
cap: ['project:read', 'node:read'],
expires_in: 60,
});actor_token_typeis required whenactor_tokenis set.- Any other key is sent as an extension parameter with a string, number, boolean or string array value. Its type is inferred from the object; pass it explicitly (
createWithTokenExchange<{ cap: string[] }>(…)) to pin it. - The
scopeof the client options is not applied: an exchange requests only the scope you pass. - The response carries
issued_token_typewhen the server sends it.
Client authentication
The second argument of every token method (create*, pollWithDeviceCode, introspect, revoke) and of deviceAuthorization.create controls how the request is authenticated:
// client id and secret in a Basic header instead of the body
token = await client.token.createWithClientCredentials({}, {
clientCredentialsAsHeader: true,
});
// a different client for this request only
token = await client.token.createWithClientCredentials({}, {
clientId: 'other-app',
clientSecret: 'other-secret',
clientCredentialsAsHeader: true,
});
// an explicit Authorization header (string or AuthorizationHeader object)
token = await client.token.createWithPassword(
{ username: 'admin', password: 'start123' },
{ authorizationHeader: { type: 'Basic', username: 'my-app', password: 'secret' } },
);
// abort or time out a single request
const controller = new AbortController();
token = await client.token.createWithClientCredentials({}, {
signal: controller.signal,
timeout: 5_000,
});| Option (TokenBaseOptions) | Type | Default | Description |
|---|---|---|---|
| clientCredentialsAsHeader | boolean | false | Send the client id and secret as Authorization: Basic … and remove client_id and client_secret from the body |
| clientId, clientSecret | string | options.clientId, options.clientSecret | The credentials for that header, for this request only. Without clientCredentialsAsHeader they are not sent |
| realmId | string | options.realmId | Realm for this request |
| authorizationHeader | string \| AuthorizationHeader | | Use this Authorization header. Takes precedence over clientCredentialsAsHeader |
| authorizationHeaderInherit | boolean | false | Keep the client's own Authorization header (set with setAuthorizationHeader) for this request |
| signal | AbortSignal | | Abort the request |
| timeout | number | the client's timeout | Abort after this many milliseconds |
Rules:
- The client's own
Authorizationheader is removed from every token, introspection, revocation and device authorization request, unlessauthorizationHeaderInheritis set and the header exists. - Otherwise
authorizationHeaderwins, then the Basic header ofclientCredentialsAsHeader(when both an id and a secret are known). Without either, the request carries noAuthorizationheader and the credentials, if any, travel in the body. - Every request is sent with
Content-Type: application/x-www-form-urlencodedandAccept: application/json. - A request that hits its
timeoutrejects with aNetworkErrorwhosecodeisETIMEDOUT; test for it withisClientErrorDueTimeoutfromhapic.
Refresh, introspect and revoke
// a new access token from a refresh token
const refreshed = await client.token.createWithRefreshToken({
refresh_token: token.refresh_token!,
});
// RFC 7662: resolves with the response body
const claims = await client.token.introspect(
{ token: refreshed.access_token, token_type_hint: 'access_token' },
{ clientCredentialsAsHeader: true },
);
// { active: true, sub: '…', exp: 1735689600, … }
// RFC 7009: resolves with the hapic Response
await client.token.revoke(
{ token: refreshed.refresh_token, token_type_hint: 'refresh_token' },
{ clientCredentialsAsHeader: true },
);introspect<T>()posts tointrospectionEndpointand resolves with the response body, typed asJwtPayloadunless you passT.revoke()posts torevocationEndpointand resolves with thehapicResponse; servers usually answer with an empty 200.- The configured client credentials are not added to these two requests. Authenticate them with
clientCredentialsAsHeader: true(usesoptions.clientIdandoptions.clientSecret), withclient_idandclient_secretin the parameters (sent in the body), withauthorizationHeader, or withauthorizationHeaderInheritand a header set on the client:
client.setAuthorizationHeader({ type: 'Bearer', token: 'service-token' });
await client.token.introspect(
{ token: 'token-to-check' },
{ authorizationHeaderInherit: true },
);Device authorization
For a device without a browser or keyboard (a CLI, a TV, a printer), RFC 8628 replaces the redirect: the device requests a user code, the user enters it on another device, and the device polls the token endpoint until the user has approved.
// 1. request a device code and a user code
const authorization = await client.deviceAuthorization.create({ scope: 'openid profile' });
// 2. show the user where to go and what to enter
console.log(`Open ${authorization.verification_uri} and enter ${authorization.user_code}`);
// or render authorization.verification_uri_complete as a QR code
// 3. poll the token endpoint until the user has approved
const controller = new AbortController();
const token = await client.token.pollWithDeviceCode(authorization, {
signal: controller.signal,
});deviceAuthorization.create(parameters?, options?)posts a form body todeviceAuthorizationEndpointand fillsclient_id,client_secret,realm_idandscopefrom the client options when you leave them out. It follows the client authentication rules of the token methods. It resolves withdevice_code,user_code,verification_uri,expires_inand, when present,verification_uri_completeandinterval.token.pollWithDeviceCode(parameters, options?)waitsintervalseconds (5 when unset), then callscreateWithDeviceCode, and repeats while the server answersauthorization_pending. Aslow_downadds 5 seconds to the interval for this and every later request. Any other error, such asaccess_deniedorexpired_token, rejects as is.- You can pass the device authorization response as it is, together with parameters the authorization server defines (e.g. Authup's
realm_name): every parameter is sent exceptinterval,expires_in,user_code,verification_uriandverification_uri_complete. Withexpires_in, polling stops once the next wait would end after that many seconds from the start of the call, and rejects with the lastauthorization_pendingorslow_downerror, so such a rejection always means the deadline passed. At least one request is always made. - Aborting
signalduring a wait rejects with itsreason; during a request it rejects with the client's abort error (NetworkError).timeoutapplies to each request, not to the whole polling. createWithDeviceCode({ device_code, ...extension })makes a single request, for your own polling loop. Noscopeis sent with the device code grant.
Userinfo
// a bare token gets the Bearer prefix
let profile = await client.userInfo.get('eyJhbGciOi…');
// a string with a space is sent as is
profile = await client.userInfo.get('Bearer eyJhbGciOi…');
// an AuthorizationHeader object
profile = await client.userInfo.get({ type: 'Bearer', token: 'eyJhbGciOi…' });
// no argument: the Authorization header set on the client
client.setAuthorizationHeader({ type: 'Bearer', token: 'eyJhbGciOi…' });
profile = await client.userInfo.get();
// { sub: '…', name: '…', email: '…' }userInfo.get<T>() sends a GET to userinfoEndpoint with Accept: application/json and resolves with the response body.
A second argument bounds or cancels the request:
const controller = new AbortController();
profile = await client.userInfo.get('eyJhbGciOi…', {
signal: controller.signal,
timeout: 5_000,
});| Option (UserInfoOptions) | Type | Default | Description |
|---|---|---|---|
| signal | AbortSignal | | Abort the request |
| timeout | number | the client's timeout | Abort after this many milliseconds |
OpenID Connect discovery
createClientWithOpenIDDiscoveryURL() requests the provider metadata and returns an OAuth2Client whose authorizationEndpoint, tokenEndpoint, introspectionEndpoint, revocationEndpoint, userinfoEndpoint and deviceAuthorizationEndpoint come from it.
import {
buildOpenIDDiscoveryURL,
createClientWithOpenIDDiscoveryURL,
} from '@hapic/oauth2';
const discoveryURL = buildOpenIDDiscoveryURL('https://auth.example.com/realms/master/');
// https://auth.example.com/realms/master/.well-known/openid-configuration
const discovered = await createClientWithOpenIDDiscoveryURL(discoveryURL, {
timeout: 10_000,
});
// the metadata has no client registration: add yours
discovered.options.clientId = 'my-app';
discovered.options.clientSecret = 'secret';
const serviceToken = await discovered.token.createWithClientCredentials();The second argument is either client options or an existing client:
- Client options (
baseURL,headers,transport,timeout, …) configure the discovery request and become therequestoptions of the returned client. - A client (a
hapicClientor any service client): the discovery request is sent with it, so its hooks run for that one request. The returned client is built fromclient.toOptions(): its defaults, its current headers (including anAuthorizationheader) and the same transport instance. Its hooks are not carried over, because hooks belong to a client instance; register them on the returned client. - A client of an older
hapiccopy withouttoOptions()falls back to itsdefaultsplus its currentAuthorizationheader. - Only these endpoints are copied.
clientId,clientSecret,redirectUriandscopestay unset, andissuerandjwks_uriare not used: the client does not validate ID tokens. buildOpenIDDiscoveryURL(baseURL)resolves.well-known/openid-configurationagainstbaseURLlike a link: keep a trailing slash to keep the last path segment (…/realms/masterwithout the slash gives…/realms/.well-known/…). Without an argument it returns/.well-known/openid-configuration.parseOpenIDProviderMetadata(metadata)turns metadata you already have into theoptionsblock.
Instances
The package keeps a registry of clients, keyed by name ('default' when you pass none):
import { OAuth2Client, isClient, setClient, useClient } from '@hapic/oauth2';
setClient(new OAuth2Client({ options: { clientId: 'my-app' } }));
// anywhere else in your code
const shared = useClient();
isClient(shared); // true| Function | Description |
|---|---|
| createClient(input?) | Create a new OAuth2Client. It is not registered |
| setClient(client, key?) | Register a client under key and return it |
| useClient(key?) | Return the client registered under key, or create one without configuration, register it and return it |
| hasClient(key?) / unsetClient(key?) | Check for or remove a registered client |
| isClient(input) | true for an OAuth2Client, also one from another copy of the package (marker Symbol.for('@hapic/oauth2/OAuth2Client')) |
The default export is a separate OAuth2Client created without configuration; it is not the one useClient() returns. More on the registry: Instance Registry.
Errors
A response with a status of 400 to 599 rejects with an HttpResponseError; a request that never got a response (network failure, abort, timeout) rejects with a NetworkError. Both are ClientErrors.
import { isClientErrorWithStatusCode, isHttpResponseError } from '@hapic/oauth2';
try {
await client.token.createWithRefreshToken({ refresh_token: 'expired' });
} catch (error) {
if (isHttpResponseError(error)) {
// RFC 6749 5.2: { error: 'invalid_grant', error_description?: '…' }
console.log(error.status, error.response?.data);
}
if (isClientErrorWithStatusCode(error, [400, 401])) {
// send the user through the authorization flow again
}
}| Guard | Matches |
|---|---|
| isHapicError | Any error thrown by hapic or a @hapic/* package |
| isClientError | Any request error (HttpResponseError or NetworkError) |
| isHttpResponseError | A 4xx/5xx response; error.response.data holds the decoded body |
| isNetworkError | No response at all |
| isClientErrorWithStatusCode(error, code \| code[]) | A response with one of these status codes |
| isClientErrorDueNetworkIssue | A request error without a response, except an abort |
buildURL() and buildAuthorizeURL() throw a plain TypeError for an endpoint that is not an absolute URL. More on errors, and on error hooks that retry a request: Errors.
API
| Export | Kind | Purpose |
|---|---|---|
| OAuth2Client | class | Client with authorize, token, userInfo, deviceAuthorization and options |
| AuthorizeAPI | class | buildURL(parameters?) |
| TokenAPI | class | create, createWithClientCredentials, createWithPassword, createWithAuthorizationCode, createWithRefreshToken, createWithDeviceCode, createWithRobotCredentials, createWithTokenExchange, pollWithDeviceCode, introspect, revoke |
| DeviceAuthorizationAPI | class | create(parameters?, options?) |
| UserInfoAPI | class | get(header?, options?) |
| buildAuthorizeURL | function | Authorize URL from an endpoint and parameters |
| createClientWithOpenIDDiscoveryURL | function | Client from a discovery document |
| buildOpenIDDiscoveryURL | function | .well-known/openid-configuration URL for a base URL |
| parseOpenIDProviderMetadata | function | Provider metadata to Options |
| createClient, useClient, setClient, hasClient, unsetClient, isClient | functions | Instances |
| isHapicError, isClientError, isHttpResponseError, isNetworkError, isClientErrorWithStatusCode, isClientErrorDueNetworkIssue | functions | Errors, re-exported from hapic |
| transformHeadersForTokenAPIRequest(headers, options?) | function | Apply the token request header rules to a Headers object: set Content-Type: application/x-www-form-urlencoded, drop the client's Authorization header unless authorizationHeaderInherit, then set authorizationHeader, or the client credentials as Basic with clientCredentialsAsHeader (see Client authentication) |
| createRequestTransformerForTokenAPIRequest(parameters, options?) | function | A hapic request transformer that applies the same header rules and, with clientCredentialsAsHeader, removes client_id and client_secret from the body. Use it for a custom request to an endpoint of the authorization server |
| buildRequestTransformersForTokenAPIRequest(client, defaults, parameters, options?) | function | The transformers of a token style request: the header rules first, then the client's default transformers. Fills clientId, clientSecret and realmId of options from defaults |
| buildRequestOptionsForTokenAPIRequest(transform, options?) | function | Request options with the transformers, Accept: application/json, and the signal and timeout of options |
| buildURLSearchParamsForTokenAPIRequest(input) | function | A form body: non empty strings as is, numbers and booleans stringified, arrays joined with spaces (audience and resource repeated per item), everything else left out |
| extendClientAuthenticationParameters(parameters, defaults) | function | Fill client_id, client_secret and realm_id of parameters from the client options |
| scopeToArray, scopeToString | functions | Convert a scope between 'a b' and ['a', 'b'] (scopeToString removes duplicates) |
| AuthorizeResponseType, AuthorizeResponseMode, AuthorizeCodeChallengeMethod, AuthorizeDisplay, AuthorizePrompt, ResponseType, TokenTypeIdentifier | enums | Parameter values |
| Options, Config, ConfigInput | types | Client configuration |
| AuthorizeParameters, AuthorizeParameterValue | types | Authorize URL parameters |
| TokenGrantParameters, Token*GrantParameters, TokenGrantResponse, TokenBaseOptions, TokenIntrospectParameters, TokenRevokeParameters, TokenDeviceCodeParameters, TokenDeviceCodePollParameters, TokenTokenExchangeParameters, TokenExtensionParameters, ClientAuthenticationParameters | types | Token requests |
| DeviceAuthorizationParameters, DeviceAuthorizationResponse | types | Device authorization requests |
| UserInfoOptions | type | Userinfo request options |
| OpenIDProviderMetadata, JwtPayload, ResponseTypeCombinations | types | Discovery and token payloads |
| default export | OAuth2Client | An unconfigured client, not the registry's 'default' |
Notes
AuthorizeParametershas an index signature for custom parameters. An object typed with aninterfacehas no implicit index signature and is not assignable to it, and neither is a type with a non-string extra property. Use atypealias, build the object inline, or spread it (buildURL({ ...parameters })). The index signature also means a misspelt key (redirect_url) is not a type error: it is sent as a custom parameter.- The token methods change the objects you pass.
create*writesclient_id,client_secret,scope,redirect_uriandrealm_idfrom the client options into your parameters object, and every token method stores the resolvedclientId,clientSecretandrealmIdin your per-request options object.deviceAuthorization.createdoes the same;pollWithDeviceCodeworks on copies. Pass fresh objects, and never reuse a token parameters object forbuildURL(). - Introspection and revocation do not send the configured client credentials by themselves. Set
clientCredentialsAsHeader: true, passclient_idandclient_secret, or set anAuthorizationheader (see Refresh, introspect and revoke). clientIdandclientSecretin the per-request options only take effect withclientCredentialsAsHeader: true. Without it they are not sent; putclient_idandclient_secretin the parameters to send them in the body.authorizationEndpointmust be absolute. A relative value throws aTypeErrorinbuildURL(), while the other endpoints may be relative tobaseURL.- The token response is reduced to the fields listed under Token grants. A
scopethe server returns is not passed on. - No PKCE generation and no ID token validation. The client sends the
code_challengeandcode_verifieryou create and returns theid_tokenas a string. Checkstateand verify ID tokens in your code. - Discovery does not copy hooks. A client passed to
createClientWithOpenIDDiscoveryURL()lends its options, headers and transport, not its hooks.
Contributing
Bug reports and pull requests are welcome in the hapic repository. Commit messages follow Conventional Commits; run npm run build, npm run test and npm run lint before you open a pull request.
License
Made with 💚
Published under MIT License.
