Skip to content
Jennifer Programming Language

oauth API reference

A generic OAuth2 client: the get-a-token half of OAuth2 (the use-a-token half is sasl XOAUTH2). Acquires and refreshes access tokens against any OAuth2 token endpoint, over http + json. Ships five flows: Client Credentials (a service authenticating as itself, with a secret or a signed client assertion), Refresh Token (trade a refresh token for a fresh access token), the Device Authorization Grant (the CLI-friendly flow: show the user a URL + code, poll the token endpoint until they approve), Authorization Code with PKCE (the browser sign-in, its redirect caught on a loopback httpd server), and the JWT Bearer grant (RFC 7523: a signed assertion, built by jwtAssertion, traded for a token - how service accounts authenticate). discover reads a provider's endpoints from its metadata document. The module is provider-neutral: presets with a provider's endpoints, and Google service-account key files, are in the @deckyard/oauthext deck. Because it builds on http (which uses net), this module needs the default jennifer binary. A token-endpoint error, a reply that is malformed (a missing or mistyped field, an empty token, a lifetime out of range), and a malformed HTTP reply surface as a catchable oauth.OAuthError (kind "oauth"): a provider's answer carries its errorCode (invalid_grant, access_denied, ...), description and HTTP status. The generic kinds pass: a socket failure (refused or reset, DNS, TLS) is http's net.NetError (kind "net"), a reply over 1 MiB or past json's decoding caps kind "limit", a stalled or overlong request "timeout", a reply cut short "closed". devicePoll, exchangeCodeWith and discoverMetadata serve a server that relays sign-ins for its own clients.

Import with import "oauth.j" as oauth;. See the oauth guide for prose and examples.

Contents

NameWhat it is
authorizeStart an authorization-code sign-in with PKCE (RFC 7636, S256): a fresh random state and code verifier, a...
authorizeWithauthorize, with more parameters for the authorization URL: a provider's own (access_type=offline and...
awaitCodeWait on a loopback httpd server for the provider's redirect, answer the browser with a short page, and re...
clientAssertionBuild a client assertion (RFC 7523 section 2.2, OpenID Connect private_key_jwt): the client proves who it...
clientCredentialsAcquire a token for the client itself (no user).
clientCredentialsJwtThe Client Credentials grant, the client authenticating with a signed assertion (from clientAssertion) in...
codeFromRedirectThe code from the URL the provider redirected the browser to, or just its query string, checked against the...
devicePollPoll the token endpoint once for a device authorization, without waiting: for a server that relays the devi...
deviceStartBegin the device flow: return the code + URL to show the user.
deviceWaitPoll the token endpoint until the user approves (or a terminal error), returning the token.
discoverRead a provider's endpoints from its metadata document (OpenID Connect Discovery, then RFC 8414) and return...
discoverMetadatadiscover, also returning the OpenID Connect UserInfo endpoint (checked like the others) and the whole met...
discoverMetadataTlsdiscoverMetadata with TLS options, as discoverTls.
discoverTlsdiscover with TLS options: the metadata is fetched with them, and the Config carries them to every later ...
exchangeCodeTrade an authorization code for a token, sending the request's PKCE code verifier and redirect URI, and the...
exchangeCodeWithexchangeCode for a sign-in whose PKCE verifier and redirect were made elsewhere: a server that trades the...
isExpiredReport whether a token has expired (30s skew buffer).
jwtAssertionBuild a signed JWT assertion for the JWT Bearer grant (RFC 7523).
jwtBearerTrade a signed assertion (from jwtAssertion) for an access token with the JWT Bearer grant (RFC 7523).
loadRead a token previously written by save.
refreshTrade a refresh token for a new access token, preserving the refresh token when the server omits it from th...
saveWrite a token to a file as JSON (its own field shape, round-trips with load; absolute expiresAt is preser...
AuthRequeststruct: One authorization-code sign-in in progress, from authorize: send the user to url, then catch the redire...
Configstruct: The OAuth2 client settings for one provider / application.
DeviceAuthstruct: A device-authorization handle: show the user verificationUri + userCode, then deviceWait polls with...
DevicePollstruct: The outcome of one device-flow poll, from devicePoll.
Discoverystruct: A provider's metadata, from discoverMetadata.
OAuthErrorstruct: A failed OAuth operation.
Tokenstruct: An issued token.

Functions

authorize

jennifer
oauth.authorize(config as Config, redirectUri as string)

Start an authorization-code sign-in with PKCE (RFC 7636, S256): a fresh random state and code verifier, and the URL to open in the user's browser. The provider sends the browser back to redirectUri with a code: catch it with awaitCode (a loopback httpd server, http://127.0.0.1:<port>/..., as RFC 8252 advises for programs on the user's machine) or read it from the redirected URL with codeFromRedirect, then call exchangeCode. The authorization URL must be https (http only on this machine); the redirect URI https, http on this machine, or a private-use scheme like com.example.app:/callback.

config
the client settings (authorizeUrl, clientId, scope)
redirectUri
the redirect URI registered with the provider
Returns AuthRequest
the sign-in in progress
Throws OAuthError
kind "oauth" if the config has no usable authorize URL or no client id, or the redirect URI is unusable

authorizeWith

jennifer
oauth.authorizeWith(
    config as Config,
    redirectUri as string,
    extra as map of string to string)

authorize, with more parameters for the authorization URL: a provider's own (access_type=offline and prompt=consent for a Google refresh token) or OpenID Connect's (nonce, login_hint, prompt). They may not replace the ones authorize sets (response_type, client_id, redirect_uri, scope, state, code_challenge, code_challenge_method).

config
the client settings (authorizeUrl, clientId, scope)
redirectUri
the redirect URI registered with the provider
extra
the added parameters
Returns AuthRequest
the sign-in in progress
Throws OAuthError
kind "oauth" as authorize, or if extra names a parameter authorize sets

awaitCode

jennifer
oauth.awaitCode(req as AuthRequest, srv as httpd.Server)

Wait on a loopback httpd server for the provider's redirect, answer the browser with a short page, and return the code. Requests for another path, carrying another state, or with a malformed or repeated parameter are answered and ignored, however many arrive. It blocks until the redirect arrives: to bound the wait, run it in a task with task.waitTimeout and httpd.shutdown the server on a timeout (the wait then throws).

req
the sign-in, from authorize; its redirect URI points at srv
srv
the listening server
Returns string
the authorization code
Throws OAuthError
kind "oauth" on a provider error (e.g. access_denied) or a redirect without a code

clientAssertion

jennifer
oauth.clientAssertion(
    alg as string,
    clientId as string,
    audience as string,
    key as bytes,
    kid as string)

Build a client assertion (RFC 7523 section 2.2, OpenID Connect private_key_jwt): the client proves who it is with a JWT signed by its own key instead of a secret. iss and sub are the client id, aud the token endpoint (audience), a random jti, valid for five minutes.

alg
the JOSE algorithm (e.g. "RS256", "ES256")
clientId
the client identifier
audience
the aud claim, usually the token endpoint URL
key
the signing key (PEM private key for RS* / ES*)
kid
the key id for the JWT header ("" for none)
Returns string
the compact signed assertion
Throws OAuthError
kind "oauth" on an empty client id or audience (jwt errors pass)

clientCredentials

jennifer
oauth.clientCredentials(config as Config)

Acquire a token for the client itself (no user).

config
the client settings
Returns Token
the issued access token
Throws OAuthError
kind "oauth" on a token-endpoint error

clientCredentialsJwt

jennifer
oauth.clientCredentialsJwt(config as Config, assertion as string)

The Client Credentials grant, the client authenticating with a signed assertion (from clientAssertion) instead of clientSecret, which is not sent.

config
the client settings (tokenUrl, clientId, optional scope)
assertion
the signed client assertion
Returns Token
the issued access token
Throws OAuthError
kind "oauth" on a token-endpoint error

codeFromRedirect

jennifer
oauth.codeFromRedirect(req as AuthRequest, redirected as string)

The code from the URL the provider redirected the browser to, or just its query string, checked against the request: a URL must go to the request's redirect URI, the state must match, and no parameter may repeat.

req
the sign-in, from authorize
redirected
the redirected URL, or its query
Returns string
the authorization code
Throws OAuthError
kind "oauth" on another redirect target, a state mismatch, a repeated parameter, a provider error (e.g. access_denied), or no code

devicePoll

jennifer
oauth.devicePoll(config as Config, deviceAuth as DeviceAuth)

Poll the token endpoint once for a device authorization, without waiting: for a server that relays the device flow to its own clients and polls on their behalf, one poll per request. deviceWait is the loop around it. The caller keeps to intervalSec (wider after "slow_down") and stops at expiresAt.

config
the client settings
deviceAuth
the handle from deviceStart (or one rebuilt from its fields)
Returns DevicePoll
the outcome: "ok" with the token, "pending", "slow_down", or "failed" with the error code and HTTP status
Throws OAuthError
kind "oauth" if the endpoint is not https, gives no usable reply, or sends a malformed error or token; a socket failure is a net.NetError (kind "net")

deviceStart

jennifer
oauth.deviceStart(config as Config)

Begin the device flow: return the code + URL to show the user.

config
the client settings
Returns DeviceAuth
the device-authorization handle
Throws OAuthError
kind "oauth" on a device-endpoint error

deviceWait

jennifer
oauth.deviceWait(config as Config, deviceAuth as DeviceAuth)

Poll the token endpoint until the user approves (or a terminal error), returning the token. Sleeps intervalSec seconds between polls, backing off on slow_down (to at most ten minutes), and never past the code's expiry.

config
the client settings
deviceAuth
the handle from deviceStart
Returns Token
the issued access token
Throws OAuthError
kind "oauth" if device authorization fails or expires, or the handle's interval is not 1 to 600 s or it has no expiry

discover

jennifer
oauth.discover(
    issuer as string,
    clientId as string,
    clientSecret as string,
    scope as string)

Read a provider's endpoints from its metadata document (OpenID Connect Discovery, then RFC 8414) and return a Config for them. The document must name exactly this issuer, and every endpoint must be https (plain http only on this machine, for a test server). deviceUrl / authorizeUrl are "" when the provider offers no such endpoint.

issuer
the issuer URL, e.g. "https://accounts.google.com"
clientId
the OAuth2 client identifier
clientSecret
the client secret ("" for a public client)
scope
the space-separated requested scopes
Returns Config
the client settings
Throws OAuthError
kind "oauth" if the issuer is not https, no metadata is found, or it is malformed or names another issuer

discoverMetadata

jennifer
oauth.discoverMetadata(
    issuer as string,
    clientId as string,
    clientSecret as string,
    scope as string)

discover, also returning the OpenID Connect UserInfo endpoint (checked like the others) and the whole metadata document, for a program that reads more of it - who signed in, the signing keys. Keep the result to skip the fetch on later sign-ins.

issuer
the issuer URL, e.g. "https://accounts.google.com"
clientId
the OAuth2 client identifier
clientSecret
the client secret ("" for a public client)
scope
the space-separated requested scopes
Returns Discovery
the client settings, the UserInfo URL and the document
Throws OAuthError
kind "oauth" as discover

discoverMetadataTls

jennifer
oauth.discoverMetadataTls(
    issuer as string,
    clientId as string,
    clientSecret as string,
    scope as string,
    tls as http.TlsOptions)

discoverMetadata with TLS options, as discoverTls.

issuer
the issuer URL
clientId
the OAuth2 client identifier
clientSecret
the client secret ("" for a public client)
scope
the space-separated requested scopes
tls
how the certificates are checked
Returns Discovery
the client settings (tls included), the UserInfo URL and the document
Throws OAuthError
kind "oauth" as discover

discoverTls

jennifer
oauth.discoverTls(
    issuer as string,
    clientId as string,
    clientSecret as string,
    scope as string,
    tls as http.TlsOptions)

discover with TLS options: the metadata is fetched with them, and the Config carries them to every later request, as for a provider whose certificate a private CA signed.

issuer
the issuer URL
clientId
the OAuth2 client identifier
clientSecret
the client secret ("" for a public client)
scope
the space-separated requested scopes
tls
how the certificates are checked
Returns Config
the client settings, tls included
Throws OAuthError
kind "oauth" as discover
jennifer
  use fs;
  import "http.j" as http;
  import "oauth.j" as oauth;

  def tls as http.TlsOptions init http.TlsOptions{caCert: fs.readBytes("ca.pem")};
  def cfg as oauth.Config init oauth.discoverTls("https://sso.lan/realms/main",
      "id", "secret", "openid", $tls);

exchangeCode

jennifer
oauth.exchangeCode(config as Config, req as AuthRequest, code as string)

Trade an authorization code for a token, sending the request's PKCE code verifier and redirect URI, and the client secret when the config has one.

config
the client settings (tokenUrl, clientId, optional clientSecret)
req
the sign-in, from authorize
code
the code from awaitCode or codeFromRedirect
Returns Token
the issued token
Throws OAuthError
kind "oauth" on a token-endpoint error

exchangeCodeWith

jennifer
oauth.exchangeCodeWith(
    config as Config,
    code as string,
    verifier as string,
    redirectUri as string)

exchangeCode for a sign-in whose PKCE verifier and redirect were made elsewhere: a server that trades the code its client caught, with the client's verifier.

config
the client settings (tokenUrl, clientId, optional clientSecret)
code
the authorization code
verifier
the PKCE code verifier (43 to 128 characters of A-Z a-z 0-9 - . _ ~, RFC 7636)
redirectUri
the redirect URI the sign-in used
Returns Token
the issued token
Throws OAuthError
kind "oauth" on an empty code, a malformed verifier, an unusable redirect URI, or a token-endpoint error

isExpired

jennifer
oauth.isExpired(token as Token)

Report whether a token has expired (30s skew buffer).

token
the token to check
Returns bool
true if the token is at or past its expiry

jwtAssertion

jennifer
oauth.jwtAssertion(
    alg as string,
    issuer as string,
    subject as string,
    audience as string,
    lifetime as int,
    extra as json.Value,
    key as bytes,
    kid as string)

Build a signed JWT assertion for the JWT Bearer grant (RFC 7523). The claims are iss = issuer, sub = subject (left out when ""), aud = audience (usually the token endpoint URL), iat = now, and exp = now + lifetime, plus any extra claims the provider wants (a scope, a jti, ...). extra may not set the five claims above. Providers bound the lifetime differently (often 1 to 60 minutes), so it is the caller's choice.

alg
the JOSE algorithm (e.g. "RS256", "ES256")
issuer
the iss claim (the client or service-account id)
subject
the sub claim ("" to leave it out)
audience
the aud claim
lifetime
seconds from now until the assertion expires (> 0)
extra
additional claims, a JSON map (json.map() for none)
key
the signing key: a PEM private key for RS* / ES*, an HMAC secret for HS*
kid
the key id for the JWT header ("" for none)
Returns string
the compact signed assertion
Throws OAuthError
kind "oauth" on a bad issuer / audience / lifetime / extra (jwt errors pass)

jwtBearer

jennifer
oauth.jwtBearer(config as Config, assertion as string)

Trade a signed assertion (from jwtAssertion) for an access token with the JWT Bearer grant (RFC 7523). Sends config.scope when set, and the client id / secret only when the config has them - a service-account assertion authenticates the client by itself, so those are usually "". deviceUrl is not used.

config
the client settings (tokenUrl, optional scope / client credentials)
assertion
the signed JWT assertion
Returns Token
the issued access token
Throws OAuthError
kind "oauth" on a token-endpoint error

load

jennifer
oauth.load(path as string)

Read a token previously written by save. A file saved before 0.26.0 has no idToken / extra and loads with them empty.

path
the file path to read
Returns Token
the loaded token
Throws OAuthError
kind "oauth" if the file is unreadable or not a saved token
Throws Error
kind "limit" for a file past fs's read cap (other generic kinds pass through too)

refresh

jennifer
oauth.refresh(config as Config, refreshToken as string)

Trade a refresh token for a new access token, preserving the refresh token when the server omits it from the reply.

config
the client settings
refreshToken
the refresh token to redeem
Returns Token
the new access token
Throws OAuthError
kind "oauth" on a token-endpoint error

save

jennifer
oauth.save(path as string, token as Token)

Write a token to a file as JSON (its own field shape, round-trips with load; absolute expiresAt is preserved). The token goes to a new owner-only (0600) file beside path, flushed to the disk, which then replaces path, and the directory is flushed after the rename: a crash or a power loss leaves the old file or the new one, and a symbolic link at path is replaced, not followed. An OAuth token is a bearer credential - the file-permission model gh / aws use for their token stores.

path
the file path to write
token
the token to persist

Structs

AuthRequest

One authorization-code sign-in in progress, from authorize: send the user to url, then catch the redirect (awaitCode or codeFromRedirect) and trade the code with exchangeCode.

jennifer
def struct AuthRequest {
    url as string,
    state as string,
    verifier as string,
    redirectUri as string
};
url
the authorization URL to open in the user's browser
state
the random value the redirect must carry back
verifier
the PKCE code verifier, sent with the code
redirectUri
the redirect URI registered with the provider

Config

The OAuth2 client settings for one provider / application.

jennifer
def struct Config {
    tokenUrl as string,
    deviceUrl as string,
    authorizeUrl as string,
    clientId as string,
    clientSecret as string,
    scope as string,
    tls as http.TlsOptions
};
tokenUrl
the token endpoint URL
deviceUrl
the device-authorization endpoint URL ("" if the provider has none)
authorizeUrl
the authorization endpoint URL, for authorize ("" if the provider has none)
clientId
the OAuth2 client identifier
clientSecret
the OAuth2 client secret
scope
the space-separated requested scopes
tls
how the endpoints' certificates are checked: the zero value verifies against the system's roots; caCert (PEM) trusts a private CA instead, as for a self-hosted provider

DeviceAuth

A device-authorization handle: show the user verificationUri + userCode, then deviceWait polls with deviceCode every intervalSec seconds.

jennifer
def struct DeviceAuth {
    deviceCode as string,
    userCode as string,
    verificationUri as string,
    intervalSec as int,
    expiresAt as int
};
deviceCode
the code polled at the token endpoint
userCode
the code the user types at the verification URL
verificationUri
the URL to show the user
intervalSec
seconds to wait between polls
expiresAt
Unix timestamp when the device code expires

DevicePoll

The outcome of one device-flow poll, from devicePoll.

jennifer
def struct DevicePoll {
    state as string,
    token as Token,
    errorCode as string,
    description as string,
    status as int
};
state
"ok" (token is set), "pending" (authorization_pending), "slow_down", or "failed" (any other answer: see errorCode and status)
token
the issued token when state is "ok"
errorCode
the provider's error code ("" when it sent none, e.g. an HTML 5xx page)
description
the provider's error_description, or what was wrong with the reply ("" when none)
status
the HTTP status of the reply

Discovery

A provider's metadata, from discoverMetadata.

jennifer
def struct Discovery {
    config as Config,
    userinfoUrl as string,
    metadata as json.Value
};
config
the client settings, as discover returns them
userinfoUrl
the OpenID Connect UserInfo endpoint ("" when the provider names none), checked like the others
metadata
the whole metadata document, for the fields the module does not read (jwks_uri, end_session_endpoint, ...)

OAuthError

A failed OAuth operation. Every error of kind "oauth" is one, so its fields are safe to read once the kind matches. When a provider answered with an OAuth error (RFC 6749 section 5.2, RFC 8628, or the authorization redirect), errorCode is its code, such as invalid_grant, access_denied or expired_token; otherwise it is "" and the message says what was wrong.

jennifer
def struct OAuthError {
    kind as string,
    message as string,
    errorCode as string,
    description as string,
    status as int
};
kind
always "oauth"
message
what went wrong, with the provider's code and description when it sent them
errorCode
the provider's error, "" when the failure is not a provider's OAuth error
description
the provider's error_description, "" when it sent none
status
the HTTP status of the provider's reply; 0 when no reply was involved (a redirect, a local check)

Token

An issued token. expiresAt is a Unix timestamp (seconds; 0 = no known expiry).

jennifer
def struct Token {
    accessToken as string,
    tokenType as string,
    refreshToken as string,
    scope as string,
    expiresAt as int,
    idToken as string,
    extra as map of string to string
};
accessToken
the bearer access token
tokenType
the token type (e.g. "Bearer")
refreshToken
the refresh token ("" if none)
scope
the scopes granted with this token
expiresAt
Unix expiry timestamp in seconds (0 = unknown)
idToken
the OpenID Connect ID token ("" if none)
extra
the response's other top-level string, number and boolean fields, as text (e.g. Salesforce's instance_url)