OAuth and OpenID Connect Authorization Code flows with S256 PKCE.
start/2 validates discovery metadata, creates high-entropy state, nonce, and
PKCE values, stores the transaction with a finite lifetime, and returns the
authorization URL. callback/3 atomically consumes state, exchanges the code
exactly once, and verifies the ID Token against the stored issuer, client,
nonce, configured algorithm, and returned access token.
start/2 can also return the transaction for the application to keep, with
no store; see "Keeping the transaction yourself" there. exchange/2 is the
token request alone, for an application that ran the authorization request
itself.
Transactions are also bound to an opaque application-supplied browser-session value, preventing a response initiated in one user agent from being used in another. The store protects protocol correlation only. Applications remain responsible for deciding whether verified claims authorize a user, creating or retaining a session, and persisting rotated tokens.
protocol: :oauth supports plain OAuth authorization without OIDC metadata
or an ID Token. PAR and DPoP are supported in either protocol mode.
Summary
Functions
Consume an authorization response and complete the code exchange.
Exchange an authorization code for tokens (RFC 6749 §4.1.3, RFC 7636 §4.5).
Begin an authorization transaction.
Types
@type store() :: AttestoClient.AuthorizationTransaction.Store.store()
@type transaction_target() :: store() | :return
Where start/2 keeps the transaction: a store, or :return to hand it back
to the caller.
Functions
@spec callback(transaction_target(), map() | String.t(), keyword()) :: {:ok, %{tokens: AttestoClient.TokenSet.t(), id_token_claims: map() | nil}} | {:error, term()}
Consume an authorization response and complete the code exchange.
The second argument may be either the original callback URI (or raw
application/x-www-form-urlencoded response body) or a string-keyed callback
parameter map. Prefer the encoded form: it is inspected before conversion to
a map and rejects repeated parameter names, including percent-encoded aliases
such as co%64e plus code. A framework-produced map cannot reveal names
that its parser already collapsed; reject duplicates at that parser or pass
the original URI/body here.
State is consumed before any token request, so replay and concurrent duplicate
callbacks fail. A malformed or ambiguous encoded response is rejected before
state is consumed.
:browser_binding is required and must equal the opaque value supplied to
start/2; a mismatch consumes state and fails before token exchange. The
client authentication option is forwarded as :client_auth; supported forms
are :none, {:client_secret_basic, secret},
{:client_secret_post, secret}, and {:private_key_jwt, jwk}.
The three-element form {:private_key_jwt, jwk, assertion_opts} accepts
:alg, :kid, :audience, :lifetime, :now, and :jti for registrations
whose client assertion differs from the defaults; :client_id is always
pinned to the stored transaction.
:resource narrows the token request to a subset of the resource indicators
the transaction was started with (RFC 8707 §2.2); by default every pinned
indicator is repeated. A value outside that set fails with
{:error, :invalid_resource} after state is consumed.
:clock_skew_seconds and :expiry_leeway_seconds set the ID Token's clock
tolerances, as in AttestoClient.IDToken.verify/2.
The ID Token's keys are fetched from the transaction's jwks_uri on each
callback. Pass issuer: {AttestoClient.Issuer, name} to use that cache's
keys instead. The cache must be the one for the issuer the transaction was
started with; any other fails with {:error, :issuer_mismatch} after state
is consumed and before token exchange.
:max_token_age_seconds and require_auth_time: true tighten the ID Token
checks, as in AttestoClient.IDToken.verify/2. The latter treats non-positive
integer auth_time as missing. require_typ: true requires a JOSE typ of
JWT or application/jwt, case-insensitively; it defaults to false.
require_kid: true requires an ID Token key identifier even with one issuer
key; with multiple keys it is always required.
:now accepts integer Unix seconds or a zero-arity function returning them.
It applies to the transaction deadline, DPoP proofs, and all ID Token time
checks. For the transaction deadline, seconds mean the last millisecond of
that second. :now_ms accepts integer Unix milliseconds or a zero-arity
function returning them and overrides only the transaction clock. Both
deadline checks read the clock, including before an authorization error is
returned and after key lookup, before the code is spent. :now_ms does not
change DPoP or ID Token NumericDates. ID Token verification reads the function after signature verification,
including any key refresh. A function is also read after the initial key
lookup to check the transaction deadline before spending the code. Store TTLs
and network timeouts still use elapsed time. Invalid :now or :require_typ
options fail before taking state, with :invalid_time or
:invalid_require_typ; a non-integer function result is :invalid_time.
:trusted_audiences lists the audiences, other than this client, that the
ID Token's aud may name, as in AttestoClient.IDToken.verify/2. It is
empty by default, so an ID Token with any additional audience is rejected.
:outbound is the exception start/2 was given, passed again
(AttestoClient.Outbound). The transaction does not carry it: without it
the token request and key fetch are held to the default HTTPS and
public-address rules, and with allow_loopback_http: true the transaction's
issuer must be a loopback host or the result is {:error, :invalid_outbound}.
A malformed value is refused before the transaction is taken.
transaction: supplies a transaction that start/2 returned (see "Keeping
the transaction yourself"). The store argument is then not consulted and may
be :return. The response's state must equal the transaction's, and the
transaction must not be past its :expires_at; either failure is
{:error, {:invalid_state, reason}}, as with a store. Nothing here makes
the transaction single use.
A timeout leaves the remote outcome unknown and the transaction consumed; do not retry an authorization code.
@spec exchange( String.t(), keyword() ) :: {:ok, AttestoClient.TokenSet.t()} | {:error, term()}
Exchange an authorization code for tokens (RFC 6749 §4.1.3, RFC 7636 §4.5).
This is the token request callback/3 makes, on its own, for an application
that ran the authorization request itself and holds the code, the
redirect_uri it used, and its PKCE verifier. It sends
grant_type=authorization_code with the code, redirect_uri,
code_verifier and client authentication, and returns the validated token
response as an AttestoClient.TokenSet.
Required options:
:token_endpoint- the authorization server's token endpoint.:issuer- the authorization server's issuer identifier.:client_id- this client.:redirect_uri- the value sent on the authorization request.:code_verifier- the PKCE verifier whose challenge was sent.
:client_auth, :dpop (with :dpop_nonce, :alg, :kid, :now),
:attestation_challenge_received, :req_options, :resolver, :outbound
and :timeout mean what they mean to callback/3. With :dpop the returned token set is
bound to that key's thumbprint. :resource adds RFC 8707 resource
indicators to the request. :scopes, when supplied, records the scopes from
the corresponding authorization request so a token response that omits
scope still yields the effective scope in the returned token set.
The caller is responsible for everything callback/3 does around the
request: matching state, the RFC 9207 iss check, and verifying a returned
ID Token with AttestoClient.IDToken.verify/2 (nonce, at_hash, issuer).
This function verifies none of those. A code is single use; do not retry
after a timeout.
@spec start( transaction_target(), keyword() ) :: {:ok, %{ :url => String.t(), :state => String.t(), :expires_in => pos_integer(), optional(:transaction) => AttestoClient.AuthorizationTransaction.t() }} | {:error, term()}
Begin an authorization transaction.
Required options are :issuer, :client_id, :redirect_uri, and an opaque
:browser_binding retained in the initiating user agent's secure, HttpOnly
application session. The same binding is mandatory at callback. The value is
protocol correlation only; authorization and session policy remain
application-owned.
:issuer is the issuer identifier, or {AttestoClient.Issuer, name} to
take the identifier and the discovery metadata from a running cache. The
transaction pins the identifier and the metadata either way.
Discovery is fetched unless :metadata is supplied. :scopes defaults to
["openid"] and must include openid. :id_token_alg defaults to "RS256"
and must match the client's registration and the provider metadata.
Additional request values may be supplied in :authorization_params, but
protocol-bound parameters and client-authentication fields cannot be
overridden, including bracket aliases decoded by web frameworks.
:resource names the protected resource(s) the token is for (RFC 8707
Resource Indicators): one absolute URI without a fragment, or a list of
them. Each is sent as a resource parameter on the authorization request
(or the pushed request), pinned in the transaction, and repeated on the
token request; callback/3 may narrow the token request to a subset. A
"resource" entry in :authorization_params is treated the same way;
supplying both is {:error, :invalid_authorization_params}.
:issuer_aliases lists extra exact strings accepted as the ID Token's iss
for a provider that issues more than one value. It is an opt-in workaround
that deviates from OIDC Core §3.1.3.7; see AttestoClient.IDToken. The
aliases are pinned in the transaction. Discovery and the RFC 9207
authorization-response iss check stay pinned to :issuer.
:outbound names deliberate exceptions to the HTTPS and public-address
rules for the issuer and the endpoints in its metadata: an issuer at a
private address (allowed_cidrs), or a loopback http identity provider
in development (allow_loopback_http). See AttestoClient.Outbound. It is
not stored in the transaction, so pass the same value to callback/3; a
callback that does not pass it applies the default rules to the endpoints
the transaction recorded.
Use protocol: :oauth for a plain OAuth flow, including OID4VCI issuance.
It does not require the openid scope, OIDC metadata, or an ID Token; the
callback returns id_token_claims: nil. The protocol is pinned in the
transaction and cannot be changed at callback.
par: true submits the request to the advertised Pushed Authorization
Request endpoint with :client_auth and :dpop. The default :auto uses
PAR when the server or selected profile requires it. par: false cannot
override a required PAR policy. DPoP keys supplied at start are bound to the transaction and
must also be supplied at callback; their thumbprint is sent as dpop_jkt.
:alg, :kid, and :now configure the DPoP proofs and must remain
compatible with the retained key and selected profile.
Set exactly one of haip: true or fapi?: true to select the stored profile.
Both require authenticated PAR, the authorization response's iss, and a
retained DPoP private key even when metadata omits the corresponding flags.
This client supports the DPoP sender constraint; it does not bind mTLS
certificate identities. FAPI requires private_key_jwt with a compatible
signing algorithm. HAIP supports the existing authenticated methods, including
client attestation according to the issuer's ecosystem policy.
Retain the same client-authentication method and signing key at callback.
Client attestation retains the client subject and instance key, so renewed
attestations and refreshed challenges are allowed. HAIP's Appendix E format
requires a bounded x5c certificate chain. The authorization server verifies
its signature, certificate trust and validity; an optional attester iss
claim is not part of the local instance binding.
The transaction records public key identity or a secret digest, never private
signing material. Callback options cannot weaken the selected profile.
Generic flows preserve existing authentication choices, require iss when
metadata advertises support, and always reject a returned issuer mismatch.
require_response_issuer: true additionally requires metadata to advertise
authorization_response_iss_parameter_supported: true before any transaction
is stored or authorization request is sent (RFC 9207 §2.4, §3). Otherwise
start/2 returns {:error, :response_issuer_not_supported}. This boolean
defaults to false; an invalid value is :invalid_require_response_issuer.
The requirement is retained in the transaction: a callback without iss
returns :missing_response_issuer, and callback options cannot disable it.
Keeping the transaction yourself
Pass :return in place of a store and nothing is stored: the result carries
the AttestoClient.AuthorizationTransaction under :transaction for the
application to keep, and callback/3 takes it back as transaction:. Every
callback check runs the same way on it, including its deadline
(:expires_at).
Two properties a store provides become the application's job:
- Confidentiality. The transaction holds the PKCE verifier and the browser binding. Encrypt it before it leaves the server, for example in an encrypted cookie; a signed but readable value exposes the verifier.
- Single use. A store deletes the transaction when it is taken. A
returned transaction can be presented to
callback/3again until it expires unless the application invalidates it, for example by deleting the cookie that holds it when the callback arrives. The authorization server still redeems a code only once.