Bookmarks
ReferenceCybersecurityBackendVerified

OAuth and OIDC

OAuth and OIDC are protocols for delegated access and for signing in through an external provider. The reference covers flows, PKCE, tokens, scopes, ID tokens, JWTs and security.

checked 1 Nov · next check 8 Nov · 46 min read

Sections
11
Reading
46 min
Languages
RU · UZ · EN
Written from
oauth.net/2

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What OAuth and OIDC are and how they work

OAuth 2.0 is a delegated access protocol: instead of a user’s password, an application gets a token with limited permissions and a limited lifetime from an authorization server. OpenID Connect (OIDC) is a layer on top of OAuth 2.0 that adds sign-in: the ID token tells the application who the user is and when they signed in.

Use OAuth when an application calls an API on behalf of a user, or a service calls an API on its own behalf. The user enters their password only at the authorization server, and the application receives a token for specific permissions that can be revoked without changing the password. If the frontend and the API are one application on one domain, OAuth between them is often unnecessary: a cookie-based session is enough, and OIDC remains a way to sign in through a provider.

OAuth defines four roles. The resource owner, usually the user, grants access. The client is the application that asks for access. The authorization server verifies the user and issues tokens, and the resource server, that is, the API, accepts requests carrying an access token. The client never sees the user’s password, and one authorization server can issue tokens for many APIs.

The abstract flow from RFC 6749; in practice, permission is requested through the authorization server by redirecting the browser to it.

What OpenID Connect adds

OpenID Connect uses OAuth 2.0 messages and adds an ID token, a signed JWT with the user’s identifier and details of how they were authenticated, and a UserInfo endpoint that returns the profile. In OIDC the authorization server is called the OpenID Provider (OP) and the client is the Relying Party (RP): the application trusts the provider to verify the user and stores no passwords.

Authorization and authentication

OAuth answers the question “what is this application allowed to do?”: the access token is addressed to the API, and to the client it is an opaque string. OIDC answers the question “who is this user?”: the ID token is addressed to the client. A common mistake is to treat the user as signed in because the application received an access token. OAuth 2.0 alone does not tell the client who was authenticated or when, and that is what OIDC is for.

How it differs from a session and a password

ApproachWhat it gives youWhen to choose it
OAuth 2.0An access token with limited permissions; the password stays with the authorization serverAn application or service calls an API on behalf of a user or on its own behalf
OpenID ConnectSign-in through a provider: an ID token and the user’s profileYou need to know who the user is without storing their password
Cookie sessionThe application server keeps the sign-in state; the browser holds only the session cookieThe frontend and the API are one application on one domain
Password given to the applicationThe application stores the password and gets access to everything at onceAvoid it: the password leaks together with the application, and access can be revoked only by changing the password

Choose OAuth when you need to give another application or service access to an API, and OIDC when you need sign-in through a provider. For an application on a single domain a session is enough, but OAuth still has advantages there: sign-in and two-factor checks live in the authorization server, and a new domain can be added without rework.

OAuth 2.1 is an IETF draft that combines OAuth 2.0 and common extensions in one document; see “Standards and their status” for the draft’s status. RFC 9700 dropped the implicit and password grants for OAuth 2.0 already; see “Flows” for why.

What to know first

  • HTTP: 302 redirects, the Authorization header, status codes 401 and 403 — see the “HTTP and REST” reference
  • TLS: OAuth servers accept requests only over HTTPS — see the “TLS and PKI” reference
  • JSON and base64url encoding: tokens and server responses are built from them

Section sources

the section is written from these pages

Cheat sheet: parameters, errors, endpoints

Endpoints, parameters, error codes and check commands for OAuth 2.0 and OpenID Connect; each value is explained in its own section. The paths /authorize and /token are examples: take the real addresses from the server metadata.

Endpoints

EndpointWhat it does
/.well-known/openid-configurationOpenID Provider metadata: endpoints, jwks_uri, scopes, algorithms
/.well-known/oauth-authorization-serverOAuth authorization server metadata (RFC 8414)
authorization_endpoint (/authorize)User sign-in and consent; the browser is redirected here
token_endpoint (/token)Issues tokens in exchange for a code, a refresh token or client credentials
jwks_uriPublic keys for verifying JWT signatures
userinfo_endpointThe user’s profile, fetched with an access token (OIDC)
introspection_endpointToken state, for the resource server (RFC 7662)
revocation_endpointToken revocation (RFC 7009)
device_authorization_endpointCodes for signing in on a device without a browser (RFC 8628)

Authorization request parameters

ParameterWhat it means
response_type=codeThe authorization code flow: the response carries a code
client_idThe client identifier; not a secret
redirect_uriWhere to send the browser back; must match the registered value character for character
scopeThe requested permissions, separated by spaces; openid is required in OIDC
stateA random value from the client; the server returns it unchanged
nonceA random OIDC value; returned inside the ID token
code_challengeThe hash of code_verifier, per PKCE
code_challenge_method=S256How code_challenge was derived; do not use plain
prompt=loginOIDC: force the user to sign in again

Token request parameters

ParameterWhat it means
grant_type=authorization_codeExchanges a code for tokens; sent together with code and code_verifier
grant_type=refresh_tokenA new access token from a refresh_token
grant_type=client_credentialsA token for the client itself, with no user
grant_type=urn:ietf:params:oauth:grant-type:device_codePolling the server in the device flow, together with device_code
code_verifierThe original PKCE string; the server compares its hash with code_challenge
resourceThe address of the API the token is for (RFC 8707)

Authorization server errors

CodeWhat it means
invalid_requestA required parameter is missing, a parameter is repeated, or the request is malformed
invalid_clientClient authentication failed; may come with status 401
invalid_grantThe code or refresh token is invalid, expired, revoked, issued to another client, or redirect_uri does not match
unauthorized_clientThe client is not allowed to use this flow
unsupported_grant_typeThe server does not support this grant_type
invalid_scopeThe scope is unknown, malformed or broader than allowed
access_deniedThe user or the server denied access
authorization_pendingDevice flow: the user has not yet confirmed the sign-in; keep polling
slow_downDevice flow: increase the polling interval by 5 seconds
login_requiredOIDC with prompt=none: the user is not signed in

API errors in the WWW-Authenticate header

CodeWhat it means
invalid_request (400)The request is malformed, or the token was sent in several ways at once
invalid_token (401)The token is expired, revoked, malformed or was issued for a different API
insufficient_scope (403)The token’s permissions are not enough; the required scope is in the scope attribute

JWT claims

ClaimWhat it means
issWho issued the token (the issuer)
subWho the token is about: a user or a client
audWho the token is for: an API or the client’s client_id
expExpiry time, in Unix seconds
nbfThe token is not accepted before this moment
iatWhen the token was issued
jtiA unique token identifier

Troubleshooting

TaskCommand
OpenID Provider metadatacurl -s https://id.example.com/.well-known/openid-configuration
OAuth server metadatacurl -s https://id.example.com/.well-known/oauth-authorization-server
A token for a servicecurl -s -u "report-job:$CLIENT_SECRET" -d grant_type=client_credentials https://id.example.com/token
An API response with headerscurl -i -H "Authorization: Bearer $ACCESS_TOKEN" https://api.example.com/orders
Ask the server about a tokencurl -s -u "orders-api:$API_SECRET" --data-urlencode "token=$ACCESS_TOKEN" https://id.example.com/introspect
Revoke a refresh tokencurl -s -u "web-app:$CLIENT_SECRET" --data-urlencode "token=$REFRESH_TOKEN" https://id.example.com/revoke

Section sources

the section is written from these pages

Flows: authorization code, PKCE and others

A grant is the way a client obtains a token. When a user is involved, use the authorization code flow with PKCE, for any kind of client; a service with no user fits client credentials, and a TV or a console tool fits device authorization. Do not use implicit or password.

Which flow to choose

ApplicationFlowWhy
Server-side web applicationAuthorization code + PKCEThe code is exchanged for tokens on the server, together with client authentication
Browser SPAAuthorization code + PKCEThere is no secret, so PKCE protects the code; safer with a BFF — see “Client types”
Mobile and desktop applicationAuthorization code + PKCESign-in happens in the system browser, and the code returns to the application
Service, scheduled job, CIClient credentialsThere is no user: the client acts on its own behalf
TV, console toolDevice authorizationThe user confirms the sign-in on a phone or computer

The authorization code flow with PKCE, step by step

In this flow tokens never pass through the browser: it carries only a one-time authorization code, and the client exchanges that code for tokens with a direct request to the authorization server. PKCE (Proof Key for Code Exchange) binds the code to whoever started the flow: the client first sends a hash of a random string and later, at the exchange, the string itself, so an intercepted code is useless.

The blue arrows are the two halves of PKCE: the hash in step 2 and the original string in step 6.
  1. The client creates a code_verifier and a state, stores them in the session, and redirects the browser to /authorize.
  2. The browser opens /authorize with response_type=code, client_id, redirect_uri, scope, state, code_challenge and code_challenge_method=S256.
  3. The authorization server authenticates the user and asks for their consent.
  4. The server redirects the browser to redirect_uri with the code and state parameters.
  5. The browser brings the code to the client; the client compares state with the stored value.
  6. The client sends POST /token with grant_type=authorization_code, code, redirect_uri and code_verifier; a confidential client also authenticates itself.
  7. The server verifies the code and code_verifier and responds with an access token and, if allowed, a refresh token.
  8. The client calls the API with an Authorization: Bearer header.
  9. The API verifies the token and responds.

Authorization request and response

httpbrowser request
GET /authorize?response_type=code  &client_id=web-app  &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback  &scope=orders%3Aread  &state=Ct9uX2Rh7Lk4zQ  &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM  &code_challenge_method=S256 HTTP/1.1Host: id.example.com

The line breaks are for readability; in reality the address is a single line. After sign-in the server sends the browser back to redirect_uri. The code is short-lived (RFC 6749 recommends at most 10 minutes) and single-use: the server must reject a second exchange.

httpauthorization server response
HTTP/1.1 302 FoundLocation: https://app.example.com/callback  ?code=SplxlOBeZQQYbYS6WxSbIA&state=Ct9uX2Rh7Lk4zQ

Exchanging the code for tokens

bashon the client’s server
curl -s https://id.example.com/token \  -u "web-app:$CLIENT_SECRET" \  -d grant_type=authorization_code \  --data-urlencode "code=$CODE" \  --data-urlencode "redirect_uri=https://app.example.com/callback" \  --data-urlencode "code_verifier=$CODE_VERIFIER"
jsonexample response
{  "access_token": "2YotnFZFEjr1zCsicMWpAA",  "token_type": "Bearer",  "expires_in": 3600,  "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",  "scope": "orders:read"}

A public client, such as a SPA or a mobile application, has no secret: instead of -u it sends client_id in the request body, and only PKCE protects the code.

PKCE: code_verifier and code_challenge

code_verifier is a random string of 43–128 characters: Latin letters, digits and the characters -, ., _, ~. RFC 7636 advises taking 32 random bytes and encoding them as base64url, which gives exactly 43 characters. For the S256 method, code_challenge is the base64url encoding, without =, of the SHA-256 hash of that string. The plain method, where code_challenge equals the string itself, is kept for compatibility: a client that supports S256 must use it.

pythonPython 3
import base64import hashlibimport secrets # 32 random bytes in base64url: 43 charactersverifier = secrets.token_urlsafe(32)digest = hashlib.sha256(verifier.encode("ascii")).digest()challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()print(verifier, challenge, sep="\n")

Test your implementation against the example from RFC 7636: the string dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk yields the code_challenge E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM.

Client credentials: a service with no user

The client gets a token for itself by presenting only its own credentials: there is no authorization request and no browser. The flow is allowed only for confidential clients, and the server must not issue a refresh token in the response; when the token expires, the client requests a new one.

bashin the service
curl -s https://id.example.com/token \  -u "report-job:$CLIENT_SECRET" \  -d grant_type=client_credentials \  -d scope=orders:read

Device authorization: signing in on a device without a browser

The device requests a pair of codes from the server, shows the user a short user_code and the verification_uri, and polls the token endpoint while the user confirms the sign-in on a phone or computer. The flow is meant for devices with limited input or no browser, not for smartphone apps: those should use the authorization code flow.

bashon the device
curl -s https://id.example.com/device_authorization \  -d client_id=tv-app \  -d scope=profile
jsonexample response
{  "device_code": "GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS",  "user_code": "WDJB-MJHT",  "verification_uri": "https://id.example.com/device",  "expires_in": 1800,  "interval": 5}
bashpolling, on the device
curl -s https://id.example.com/token \  -d grant_type=urn:ietf:params:oauth:grant-type:device_code \  -d device_code=GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS \  -d client_id=tv-app

Until the user has finished, the server responds with authorization_pending, and the device repeats the request no more often than every interval seconds (5 by default). On slow_down, increase the interval by 5 seconds; expired_token means the codes have expired and the flow must start again; access_denied means the user refused.

Implicit and password: why they are gone

Implicit (response_type=token) returns the access token directly in the redirect URI: the token can leak or be substituted, and it cannot be bound to the client. Password (Resource Owner Password Credentials) makes the user type their password into the application itself and does not work with two-factor sign-in. The authorization code flow with PKCE solves both problems: tokens travel from the server to the client directly, and the user enters their password only at the authorization server.

Section sources

the section is written from these pages

Access and refresh tokens

An access token is a short-lived pass to an API: the client sends it in the Authorization: Bearer header, and anyone who holds it can use it. A refresh token lives longer: with it, the client gets new access tokens from the authorization server without involving the user.

How to send an access token

Send the token in the Authorization header with the Bearer scheme: every resource server must support this method. RFC 6750 also describes an access_token parameter in a form body and in the URL, but URLs end up in logs, so never put a token in a URL. Use only one method per request: sending the token in both the header and the body causes an invalid_request error. Issue access tokens for an hour or less: a short lifetime limits the damage from a leak.

bashon the client
curl https://api.example.com/orders \  -H "Authorization: Bearer $ACCESS_TOKEN"

Opaque tokens and JWTs

The authorization server chooses the access token format. An opaque token is a random string: only the server knows what is behind it, and the API asks the server through introspection. A JWT per RFC 9068 carries its data and is signed, so the API can verify it on its own, using the authorization server’s public keys.

JWT fieldWhat it holds
typ in the headerat+jwt: distinguishes an access token from an ID token
issThe issuer: the authorization server
audThe API the token was issued for
subThe user or, in client credentials, the client itself
client_idThe client that obtained the token
exp, iatExpiry time and issue time
jtiA unique token identifier
scopeThe granted permissions, separated by spaces, if any were requested

The API validates a JWT access token as follows: typ is at+jwt, iss matches the issuer from the metadata, aud contains this API’s identifier, the signature is valid for the authorization server’s keys, alg is not none, and exp has not passed. If any check fails, the response is an invalid_token error.

Introspection: asking the server about a token

The resource server sends the token to the introspection endpoint and learns its state: active and, for a valid token, scope, client_id, sub, aud and exp. The request itself must also be authorised, usually by authenticating the API as a client; otherwise the endpoint could be used to probe for valid tokens.

bashon the resource server
curl -s https://id.example.com/introspect \  -u "orders-api:$API_SECRET" \  --data-urlencode "token=$ACCESS_TOKEN" \  -d token_type_hint=access_token
jsonexample response
{  "active": true,  "client_id": "web-app",  "scope": "orders:read",  "sub": "248289761001",  "aud": "https://api.example.com/",  "iss": "https://id.example.com",  "exp": 1793451600}

For an expired, revoked or foreign token the answer is always the same, {"active": false}, with no reason given. The response can be cached, but then a revoked token will still be treated as valid for some time.

Renewal and rotation

When the access token has expired, the client sends the refresh token to the token endpoint with grant_type=refresh_token; a confidential client authenticates as well. This cannot widen the permissions: the scope in the request must be no broader than what the user granted.

bashon the client’s server
curl -s https://id.example.com/token \  -u "web-app:$CLIENT_SECRET" \  -d grant_type=refresh_token \  --data-urlencode "refresh_token=$REFRESH_TOKEN"

Along with the new access token, the server may issue a new refresh token. This is rotation. The client must then discard the old token and store the new one, and the server may revoke the old one: if a stolen token is presented again, the server responds with invalid_grant. For rotation requirements for SPAs and mobile applications, see “Security”.

AT is the access token, RT is the refresh token.

Revoking a token

When the user signs out of the application, revoke the refresh token at the revocation endpoint (RFC 7009). The server responds with 200 both for a successful revocation and for an unknown token. After revoking a refresh token, the server should also revoke the access tokens from the same grant, if it can revoke access tokens at all.

bashon the client’s server
curl -s https://id.example.com/revoke \  -u "web-app:$CLIENT_SECRET" \  --data-urlencode "token=$REFRESH_TOKEN" \  -d token_type_hint=refresh_token

A bearer token works for anyone who steals it; tokens bound to the client’s key, DPoP and mTLS, are covered in “Security”. Where to store tokens in a browser or a mobile application depends on the client type — see “Client types”.

Section sources

the section is written from these pages

Scopes

A scope is a space-separated list of values. The client uses it to ask for specific permissions, and the authorization server uses it to report which permissions it granted. The server may grant less than was requested, so the client reads scope from the response and the API checks permissions on every request.

The authorization server defines the scope values; they are case-sensitive, but their order does not matter. If the client sends no scope, the server applies a default or responds with invalid_scope. If the granted permissions differ from the requested ones, the server must return scope in the token response. For example, the client requested orders:read orders:write, but the user allowed read access only:

jsontoken endpoint response
{  "access_token": "2YotnFZFEjr1zCsicMWpAA",  "token_type": "Bearer",  "expires_in": 3600,  "scope": "orders:read"}

Designing scopes

  • Split permissions by resource and action: orders:read, orders:write, admin:org. A scope says what is allowed, not where: the API address has its own parameter, resource.
  • Request only the permissions you need: the server should limit a token to the minimum the application requires, so a leaked token does less damage.
  • Do not encode amounts, account numbers or other operation details in a scope: fine-grained permissions use authorization_details.
  • Check the scope in every API handler: a token may carry fewer permissions than the client requested.

Standard OpenID Connect scopes

ScopeWhat it grants
openidRequired in an OpenID Connect request: without it, the server’s behaviour is undefined
profileProfile: name, given_name, family_name, preferred_username, picture, locale and others
emailemail and email_verified
phonephone_number and phone_number_verified
addressPostal address: the address claim
offline_accessA refresh token, for access to UserInfo while the user is offline; requires explicit consent

When it issues an access token, the provider returns the claims from profile, email, phone and address through the UserInfo endpoint. It may omit some of them, and that is not an error: check that a field is present before you use it.

Audience: which API a token is for

A scope answers “what is allowed”, but not “where”. To stop a token for one API from being presented to another, the token is restricted to an audience: the client passes the API address in the resource parameter (RFC 8707), the server restricts the token to that audience (in a JWT, the aud claim), and the API rejects tokens issued for a different audience. The server rejects an unknown or invalid resource with the invalid_target error.

bashin a service
curl -s https://id.example.com/token \  -u "report-job:$CLIENT_SECRET" \  -d grant_type=client_credentials \  -d scope=orders:read \  --data-urlencode "resource=https://api.example.com/"

Fine-grained permissions: authorization_details

When “write orders” is not enough and you need “transfer 45 euros to payee A”, use Rich Authorization Requests (RFC 9396). The authorization_details parameter is an array of JSON objects, each with a required type field and further fields defined by the specific API.

jsonauthorization_details value
[  {    "type": "payment_initiation",    "actions": ["initiate"],    "locations": ["https://bank.example.com/payments"],    "instructedAmount": {"currency": "EUR", "amount": "45.00"}  }]

Checking scopes on the resource server

The API checks every request: the token is valid, was issued for this API, and the required permission is in scope. If it is missing, the request is rejected; the 403 response with the insufficient_scope code is covered in the “Common errors and troubleshooting” section.

pythonon the resource server
def require_scope(claims: dict, needed: str) -> None:    # scope is a space-separated string of values    granted = claims.get("scope", "").split()    if needed not in granted:        raise PermissionError(f"scope {needed} required")  require_scope({"scope": "orders:read"}, "orders:read")

Section sources

the section is written from these pages

OpenID Connect

OpenID Connect (OIDC) is a sign-in layer on top of OAuth 2.0. The client adds scope=openid to the authorization request and receives, along with the access token, an ID token: a signed JWT stating who the user is and when they signed in. A sign-in counts as complete only after the ID token has been validated.

The flow is the same as in OAuth: authorization code with PKCE. OIDC adds scope=openid, the nonce parameter, an ID token in the token endpoint response, a UserInfo endpoint that returns the profile, and a provider metadata document. Request parameters control the sign-in behaviour: prompt=login forces the user to sign in again; prompt=none forbids the provider from showing any interface, so if the user is not signed in, the response is a login_required error; and max_age sets, in seconds, how old the sign-in may be.

httpbrowser request
GET /authorize?response_type=code  &client_id=web-app  &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback  &scope=openid%20profile%20email  &state=Ct9uX2Rh7Lk4zQ  &nonce=n-0S6_WzA2Mj  &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM  &code_challenge_method=S256 HTTP/1.1Host: id.example.com

ID token

An ID token is a JWT signed by the provider. The claims iss, sub, aud, exp and iat are always present; nonce is present if the client sent one in the request, and auth_time if the client asked for max_age.

ClaimMeaning
issIssuer: the provider’s address, character for character the same as issuer in the metadata
subA stable identifier for the user at this provider, up to 255 characters
audRecipients of the token; must contain the client’s client_id
expExpiry time; after it the token is not accepted
iatIssue time
nonceThe value from the authorization request, which protects against replay
auth_timeWhen the user last authenticated
acr, amrThe level and methods of authentication, for example password and one-time code
jsonID token payload
{  "iss": "https://id.example.com",  "sub": "248289761001",  "aud": "web-app",  "nonce": "n-0S6_WzA2Mj",  "exp": 1793448600,  "iat": 1793448000,  "auth_time": 1793447990}

Validating an ID token

The client validates the ID token before it creates a session for the user: the signature (with the provider’s key), the issuer, the audience, the expiry time and the nonce. Any mismatch means the sign-in is refused. The specification allows skipping signature validation for an ID token received directly from the token endpoint over TLS, but requires it for a token that arrived any other way. Libraries such as PyJWT validate the signature by default, so it is simpler to always do so.

The client caches the metadata and keys, and fetches the keys again when it meets an unfamiliar kid.
  1. The client fetches the provider metadata and checks that its issuer equals the issuer address to which it appended /.well-known/openid-configuration.
  2. The client fetches the key set from jwks_uri.
  3. The client exchanges the code for tokens and receives id_token.
  4. The signature is verified with the key from the set that has the same kid as the token header; the algorithm comes from a list fixed in code, RS256 by default.
  5. iss is character for character equal to the provider’s issuer.
  6. aud contains the client’s client_id, and no other audiences that the client does not trust.
  7. The current time is before exp, and iat is not too far in the past.
  8. nonce equals the value the client stored when it sent the authorization request. If the client requested max_age, it also checks auth_time: the sign-in was recent enough.
pythonPython, PyJWT
import jsonimport urllib.request import jwt ISSUER = "https://id.example.com"CLIENT_ID = "web-app" with urllib.request.urlopen(    f"{ISSUER}/.well-known/openid-configuration", timeout=10) as response:    config = json.load(response)if config["issuer"] != ISSUER:    raise RuntimeError("issuer mismatch")jwks = jwt.PyJWKClient(config["jwks_uri"])  def verify_id_token(id_token: str, expected_nonce: str) -> dict:    key = jwks.get_signing_key_from_jwt(id_token)    claims = jwt.decode(        id_token,        key,        algorithms=["RS256"],        audience=CLIENT_ID,        issuer=ISSUER,        # allowance for clock skew, in seconds        leeway=60,        options={"require": ["iss", "sub", "aud", "exp", "iat"]},    )    if claims.get("nonce") != expected_nonce:        raise jwt.InvalidTokenError("nonce mismatch")    return claims

PyJWKClient selects the key by the kid in the token header, and if that kid is unknown, it fetches the JWKS again; this is how the client survives the provider rotating its keys. The algorithms list is fixed in code: the algorithm named in the token header is never trusted.

UserInfo endpoint

The client gets the user’s profile by calling userinfo_endpoint with the access token. The response always contains sub: compare it with sub from the ID token, and do not use the response if they differ.

bashon the client’s server
curl -s https://id.example.com/userinfo \  -H "Authorization: Bearer $ACCESS_TOKEN"
jsonexample response
{  "sub": "248289761001",  "name": "Dilnoza Karimova",  "email": "dilnoza@example.com",  "email_verified": true}

Discovery: metadata and keys

The provider publishes its metadata at issuer + /.well-known/openid-configuration: endpoint addresses, jwks_uri, and the supported scopes and algorithms. The issuer value in the document must match, character for character, the address to which this suffix was appended, and the iss in ID tokens. If issuer contains a path, the suffix is appended at the end: https://id.example.com/tenant1/.well-known/openid-configuration.

bashon your own machine
curl -s https://id.example.com/.well-known/openid-configuration
jsonresponse excerpt
{  "issuer": "https://id.example.com",  "authorization_endpoint": "https://id.example.com/authorize",  "token_endpoint": "https://id.example.com/token",  "userinfo_endpoint": "https://id.example.com/userinfo",  "jwks_uri": "https://id.example.com/jwks.json",  "scopes_supported": ["openid", "profile", "email"],  "id_token_signing_alg_values_supported": ["RS256", "ES256"]}

Authorization server metadata under RFC 8414 lives at /.well-known/oauth-authorization-server, and this suffix is inserted between the host and the path: for https://id.example.com/tenant1, the document is at https://id.example.com/.well-known/oauth-authorization-server/tenant1.

A provider rotates keys like this: it adds a new key to the JWKS, starts signing tokens with it under a new kid, and keeps the old key in the set for a while. When a client meets an unfamiliar kid, it fetches jwks_uri again.

Signing out

OIDC Core does not describe signing out; the OpenID Foundation has separate specifications for it: RP-Initiated Logout, Front-Channel Logout and Back-Channel Logout.

Section sources

the section is written from these pages

JWT, JWS and JWKS

A JWT (JSON Web Token) is a compact string of base64url parts separated by dots. A signed JWT (JWS) has three: a header, a payload containing the claims, and a signature. The signature protects against tampering but does not hide the data: anyone who holds a JWT can read it.

The header and payload are JSON encoded as base64url. The signature is computed over the first two parts together with the dot between them, so changing any character in them invalidates the signature. Base64url can be decoded without a key: it is encoding, not encryption.

The header and payload can be read without a key; a key is needed only to verify the signature.

Inspecting a token

For debugging, decode the token locally. Do not paste production tokens into third-party decoder websites: the contents are not encrypted, and the token itself remains valid until exp.

pythondecode_jwt.py
import base64import jsonimport sys  def part(segment: str) -> dict:    # JWT’s base64url has no trailing = padding    padded = segment + "=" * (-len(segment) % 4)    return json.loads(base64.urlsafe_b64decode(padded))  header, payload, _ = sys.argv[1].split(".")print(json.dumps(part(header), indent=2))print(json.dumps(part(payload), indent=2))
bashon your own machine
python3 decode_jwt.py "$ID_TOKEN"

Signing algorithms

algHow it worksWhen to use
RS256RSA with SHA-256: sign with the private key, verify with the public keyAsymmetric signature; the RSA key must be at least 2048 bits
ES256ECDSA on the P-256 curveAsymmetric signature; a predictable per-signature nonce reveals the private key, so the library should derive it as RFC 6979 specifies
Ed25519EdDSA on the Ed25519 curveAsymmetric signature; RFC 9864 deprecated the older name EdDSA, but PyJWT still uses it
HS256HMAC with SHA-256 and a shared secretOne secret both signs and verifies, so the verifier can also issue tokens. The secret is not a password and must be at least 32 bytes
noneNo signatureDo not accept it: the library should reject it unless you explicitly allow it

With an asymmetric algorithm, the authorization server signs tokens with a private key, while APIs and clients verify them with the public key from the JWKS and cannot issue tokens themselves.

JWK and JWKS

Public keys are published in JWK (JSON Web Key) format: kty is the key type (RSA, EC), use is the purpose (sig for signing, enc for encryption), kid is the identifier, and alg is the algorithm; an RSA key also has the modulus n and the exponent e. A JWKS (JWK Set) is a JSON object with a keys array. The JWT header carries a kid, and the verifier picks the key with the same kid from the set.

jsonjwks.json, key shortened
{  "keys": [    {      "kty": "RSA",      "use": "sig",      "kid": "2026-10",      "alg": "RS256",      "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx...",      "e": "AQAB"    }  ]}

Validating a JWT

Validating a JWT means more than checking the signature. RFC 8725 requires an application to:

  1. Fix the list of allowed algorithms in code and never trust alg from the token; each key is used for exactly one algorithm.
  2. Verify the signature with the keys of the issuer named in iss, and check iss itself against a list of trusted issuers.
  3. Check aud and reject a token issued for a different audience.
  4. Check exp and nbf, allowing a couple of minutes for clock skew.
  5. Tell token types apart by typ, the set of claims or the keys, so that an ID token cannot pass as an access token.
  6. Not trust kid, jku and x5u: kid can carry an injection into a database query, and an address from jku can lead to SSRF.
pythonwrong
claims = jwt.decode(token, options={"verify_signature": False})
pythoncorrect
claims = jwt.decode(    token,    signing_key,    algorithms=["RS256"],    audience="https://api.example.com/",    issuer="https://id.example.com",)

Without signature validation, no claim in a token can be trusted: RFC 8725 requires rejecting a JWT if any of its cryptographic checks fails. Reading a token without validating it is acceptable only for debugging.

Encrypted JWT (JWE)

If the contents must be hidden, the JWT is encrypted using JWE (JSON Web Encryption). A token that is signed first and then encrypted is a Nested JWT: to process it, you perform both operations, the outer one and the inner one.

Section sources

the section is written from these pages

Client types

A client is confidential if it can keep a secret, which means code running on a server. It is public if it cannot: a browser SPA, or a mobile or desktop app. The type determines client authentication, where tokens are stored and the architecture: for an SPA, the most reliable choice is a BFF, which keeps tokens out of the browser.

RFC 6749 describes three profiles. A web application on a server is a confidential client: the secret and tokens are stored on the server and are not visible to the user. A browser-based application and a native application on a device are public clients: anything embedded in them can be extracted, though a native app can protect the tokens it receives with platform facilities. The authorization server fixes the client type at registration; the client does not declare it in a request.

In the server-side setups, the browser holds no tokens at all.

Server-side web application

The client runs on the server, exchanges the code for tokens itself and keeps them in a server-side session, while the browser receives only a cookie. A client secret is acceptable, but RFC 9700 recommends authenticating the client asymmetrically: with mTLS (RFC 8705) or a JWT signed with the client’s private key (private_key_jwt).

SPAs: three patterns from RFC 10017

RFC 10017 describes three architectures for browser-based applications, from the most secure to the least:

PatternWhere the tokens areWhen
BFF (backend for frontend)Only on the BFF server; the browser holds a session cookie, and the BFF attaches the token to API requestsStrongly recommended for business applications and personal data
Token-mediating backendThe backend obtains the tokens but hands the access token to the browserWhen proxying all requests through a BFF is not possible
Client entirely in the browserAll tokens in the browserNot recommended for business applications and personal data

In the browser-only pattern, a malicious script on the page (XSS) steals both the access token and the refresh token; with a BFF it can only send requests on the user’s behalf from the open tab. The BFF must set the session cookie with the Secure and HttpOnly flags; SameSite=Strict, the path /, no Domain attribute and the __Host-Http- prefix are also recommended:

httpBFF response
Set-Cookie: __Host-Http-sid=k3x9; Path=/; Secure; HttpOnly; SameSite=Strict

If tokens do live in the browser: any script from the same origin can read localStorage and sessionStorage, in-memory storage is lost on reload, and a Web Worker hides the refresh token but not the access token. Storing a token in a cookie set from JavaScript is not recommended. No option protects against XSS: malicious code can start a new flow and obtain fresh tokens.

Mobile and desktop apps

  • Sign in only through an external browser, either the system browser or its in-app tab, never through a WebView: an app with an embedded browser can see the user’s password and cookies.
  • Use PKCE: a native app is a public client, and a secret embedded in the build can be extracted, so it does not count as a secret.
  • Prefer an https redirect URI on your own domain that is bound to the app in the OS: the OS then guarantees which app receives the code.
  • Build a custom URI scheme from your domain name in reverse, for example com.example.app:/oauth2redirect; the server should reject a scheme without a dot, such as myapp.
  • A desktop app can receive the response at http://127.0.0.1:{port}/: the server must allow any port, and using localhost instead of the IP address is not recommended.
textredirect_uri options
https://app.example.com/oauth2redirectcom.example.app:/oauth2redirecthttp://127.0.0.1:51004/oauth2redirect

Registering a client

At registration, specify the client type and the full redirect_uri values, including the path: the server compares them with the request character for character, with no wildcards, and for loopback addresses only the port may vary. For how to set up an OAuth client and token validation in a framework, see the Django reference (the “REST API with Django REST framework” section), the FastAPI reference, and the “Java and Spring” reference (the “Security” sections).

Section sources

the section is written from these pages

Security

The main threats to OAuth are interception and substitution of the authorization code, token leakage through URLs, logs and Referer, forged responses (CSRF), and authorization server impersonation (mix-up). RFC 9700 closes them with a few rules: PKCE for everyone, exact redirect_uri matching, and no implicit or password grants.

Authorization code and redirect_uri

  • Use PKCE with S256 in every client that uses the authorization code flow, confidential clients included: PKCE stops an intercepted code from being injected or used. The plain method exposes the code_verifier in the request itself.
  • On the authorization server, reject a code_verifier if the authorization request had no code_challenge; otherwise an attacker can strip the code_challenge and bypass PKCE (a PKCE downgrade).
  • Compare redirect_uri with the registered value character by character. The only exception is the port in loopback addresses for native apps.
  • Do not leave open redirectors: endpoints that send the browser to a URL taken from a parameter. They are used to steal codes and tokens.
  • Defend against CSRF with PKCE, if the server supports it, a nonce in OIDC, or a single-use state bound to the user’s browser.
  • Do not allow http redirect URIs: the authorization response must not travel unencrypted. The exception is loopback addresses for native apps.

Multiple authorization servers: mix-up

A client that works with two or more authorization servers can be tricked by an attacker into talking to a malicious one and handing over a code issued by an honest one. The defence is the iss parameter in the authorization response (RFC 9207): the client remembers which server it sent the request to and compares iss with that server’s issuer from its metadata. A server announces support for the parameter with the authorization_response_iss_parameter_supported flag. In OIDC, the iss claim in the ID token can play the same role, but only if the ID token arrives directly in the authorization response, for example with response_type=code id_token.

httpauthorization server response
HTTP/1.1 302 FoundLocation: https://app.example.com/callback?code=x1848ZT64p4I  &state=ZWVlNDBlYzA1NjdkMDNh&iss=https%3A%2F%2Fid.example.com

Token leakage

  • Do not pass an access token in the URL: URLs end up in logs, browser history and the Referer header. Use the Authorization header only.
  • The page the browser returns to after sign-in must not load third-party resources or contain external links; also give it Referrer-Policy: no-referrer.
  • Do not use the password grant (MUST NOT) or the implicit grant (SHOULD NOT): the first hands the password to the client, the second puts the token in the redirect URL.
  • Limit tokens: request the minimum scope and a single audience in aud, so a stolen token works against only one API.
bashwrong
curl "https://api.example.com/orders?access_token=$ACCESS_TOKEN"
bashcorrect
curl https://api.example.com/orders \  -H "Authorization: Bearer $ACCESS_TOKEN"

Refresh tokens for public clients

For public clients, the server must either bind the refresh token to the client’s key or issue a new one on every refresh (rotation). With rotation, the old token stops working; if it is presented again, the server detects the leak and revokes the active token, so the legitimate client has to sign in again. Unused refresh tokens should expire.

Sender-constrained tokens: DPoP

DPoP (RFC 9449) binds access tokens, and for public clients refresh tokens too, to the client’s key pair; these are sender-constrained tokens. With every request the client attaches a DPoP header: a JWT with typ: dpop+jwt, the public key in its header, the method in htm, the URL in htu, the time in iat, a unique jti, and, when calling an API, a hash of the token in ath. The token is sent with the DPoP scheme instead of Bearer, and the API accepts it only if the proof is signed with the same key the token is bound to.

httpclient request to the API
GET /orders HTTP/1.1Host: api.example.comAuthorization: DPoP Kz~8mXK1EalYznwH-LC-1fBAo.4Ljp~zsPE_NeO.gxUDPoP: eyJ0eXAiOiJkcG9wK2p3dCIsImFsZyI6IkVTMjU2IiwiandrIjp7...

Another option is mTLS (RFC 8705): the token is bound to the thumbprint of the client certificate in the TLS connection. mTLS cannot be used in a SPA; DPoP is designed for such clients.

Client authentication and metadata

Authenticate confidential clients asymmetrically, with mTLS or private_key_jwt: the authorization server then has no secrets to store that could leak. Publish server metadata as defined in RFC 8414 and configure clients from it, which means fewer URL mistakes and easier key rotation. JWT validation errors (alg: none, algorithm substitution, an unchecked aud) are covered in the “JWT, JWS and JWKS” section.

Section sources

the section is written from these pages

Common errors and diagnostics

First find where the flow broke. A sign-in error arrives as error and error_description parameters in the redirect_uri, a token exchange error as a JSON response from /token, and an API refusal as a WWW-Authenticate header. Rely on the code in error: it is defined in the RFCs and is the same on every server, whereas each server words error_description in its own way.

Order of checks

  1. The redirect URL: whether it contains error, and whether state matches the saved value.
  2. If the browser did not return to redirect_uri and the server showed its own error page, client_id or redirect_uri is wrong.
  3. The /token response: the HTTP status and the error field.
  4. The API response: the WWW-Authenticate header and its error attribute.
  5. The token contents: iss, aud, exp, scope; decode it yourself.
bashon the client’s server
curl -si https://id.example.com/token \  -u "web-app:$CLIENT_SECRET" \  -d grant_type=authorization_code \  --data-urlencode "code=$CODE" \  --data-urlencode "redirect_uri=https://app.example.com/callback" \  --data-urlencode "code_verifier=$CODE_VERIFIER"
textexample output
HTTP/1.1 400 Bad RequestContent-Type: application/jsonCache-Control: no-store {"error": "invalid_grant"}

invalid_grant

Cause: the authorization code or refresh token was not accepted. It has expired, been used or revoked, or been issued to another client; the redirect_uri in the /token request differs from the one in the authorization request; or the code_verifier does not match the code_challenge.

  • Exchange the code immediately and only once; if it fails, start sign-in again
  • Send the same redirect_uri to /token as in the authorization request, character for character
  • Keep the code_verifier in the session of the browser that started sign-in: if you sign in in two tabs, one tab’s string does not match the other tab’s code
  • After rotation, use the new refresh token; the server rejects the old one

invalid_client

Cause: the server could not authenticate the client, because of a wrong secret, an unknown client or an unsupported authentication method. If the client sent credentials in the Authorization header, the response is 401 with a WWW-Authenticate header. Check the secret and send credentials in one way only, in the header or in the body but not both: two methods in one request produce invalid_request.

invalid_request on the authorization request

Cause: a required parameter is missing, a parameter is repeated, or it has an invalid value. For example, the server requires PKCE but the request has no code_challenge, or the client sent a method the server does not support; error_description usually says so.

unauthorized_client

Cause: the client is not allowed to use this flow, for example client credentials for a client registered as a SPA. Enable the flow in the client settings on the authorization server, or choose another one. If the server does not recognise the grant_type at all, the response is unsupported_grant_type.

invalid_scope

Cause: the requested scope is unknown, malformed or broader than the client is allowed. Compare the request with the scopes allowed for the client on the authorization server and remove the extra ones.

access_denied

Cause: the user refused consent, or the authorization server rejected the request under its own policy. This is not a failure: tell the user that access was not granted and offer to try again.

invalid_token

Cause: the API did not accept the access token. It has expired, been revoked, is malformed, or was issued for another API. The response is 401 with an error attribute in WWW-Authenticate; the client can obtain a new token and retry the request.

bashon your own machine
curl -i https://api.example.com/orders \  -H "Authorization: Bearer $ACCESS_TOKEN"
textexample output
HTTP/1.1 401 UnauthorizedWWW-Authenticate: Bearer realm="example",  error="invalid_token",  error_description="The access token expired"

If WWW-Authenticate arrives without error, the request carried no token at all. Check that the client adds the Authorization header and that no proxy in front of the API strips it.

insufficient_scope

Cause: the token is valid but its permissions are not enough. The response is 403, and the required scope is in the scope attribute of the WWW-Authenticate header. Request a token with that scope; the user will have to give consent again.

ID token fails validation

Cause: one of the claims does not match. Most often:

What is wrongCauseWhat to do
issThe issuer differs by even one character, for example a trailing /Take issuer from the metadata and compare the strings character by character
audThe token has a different client_id, for example that of a client in another environmentCheck the client_id in the application settings
exp, iatThe clock on the client’s server is fast or slowSynchronise the time and allow a leeway of a couple of minutes
nonceThe value from the request was not saved, or sign-in ran in two tabsKeep the nonce in the session of the browser that started sign-in
SignatureThe provider rotated its key and the client holds an old JWKSReload jwks_uri when you meet an unknown kid

Section sources

the section is written from these pages

Standards and their status

OAuth 2.0 is defined by RFC 6749 and RFC 6750 from 2012, both Proposed Standards. The security rules that are mandatory today are collected in RFC 9700 (BCP 240, January 2025), which supplements them. OpenID Connect is a set of OpenID Foundation specifications: OIDC Core 1.0 with errata set 2. OAuth 2.1 is still an IETF draft.

DocumentWhat it definesStatusObsoleted or updated by
RFC 6749OAuth 2.0: roles, flows, endpoints, errorsProposed StandardUpdated by RFC 8252, 8996, 9700
RFC 6750Bearer tokens and the WWW-Authenticate headerProposed StandardUpdated by RFC 8996, 9700
RFC 9700 (BCP 240)OAuth 2.0 security best current practiceBest Current PracticeUpdates RFC 6749, 6750 and 6819
RFC 7636PKCEProposed Standard—
RFC 8628Flow for devices without a browserProposed Standard—
RFC 8252, RFC 10017 (BCP 212)OAuth for native and browser-based appsBest Current PracticeRFC 8252 updates RFC 6749
RFC 8414Authorization server metadataProposed Standard—
RFC 7662, RFC 7009Token introspection and revocationProposed Standard—
RFC 9068JWT profile for access tokensProposed Standard—
RFC 9449, RFC 8705Binding tokens to a key: DPoP and mTLSProposed Standard—
RFC 9207The iss parameter in the authorization responseProposed Standard—
RFC 7519, 7515, 7517, 7518JWT, JWS signatures, JWK keys, JWA algorithmsProposed StandardRFC 7519 is updated by RFC 7797 and 8725, RFC 7518 by RFC 9864
RFC 8725 (BCP 225)JWT best current practiceBest Current Practice—
OpenID Connect Core 1.0 and Discovery 1.0Sign-in, ID token, UserInfo, provider metadataFinal, errata set 2Also ISO/IEC 26131:2024 and 26132:2024
draft-ietf-oauth-v2-1-17OAuth 2.1Internet-DraftWill replace RFC 6749 and 6750 if approved

What changed in recent revisions

  • 31 October 2026: draft-ietf-oauth-v2-1-17 brings the RFC 10017 requirements for browser-based apps into OAuth 2.1. The previous revision removed the PKCE plain method and made the iss parameter in the authorization response mandatory for the server. The draft expires on 4 May 2027.
  • August 2026: RFC 10017 (BCP 212) describes the BFF, token-mediating backend and browser-only client patterns, token storage in the browser, and limits on refresh token lifetime for browser-based apps.
  • October 2025: the International Telecommunication Union (ITU) published OpenID Connect Core 1.0 with errata set 2.
  • January 2025: RFC 9700 (BCP 240) requires PKCE for all clients, exact redirect_uri matching, no password grant, no implicit grant, and rotation or binding of refresh tokens for public clients.
  • December 2023: errata set 2 for OpenID Connect Core 1.0 and Discovery 1.0, with corrected editions of the specifications.

Outdated practices that are still quoted

  • The implicit grant (response_type=token): SHOULD NOT in RFC 9700, MUST NOT for browser-based clients in RFC 10017, and absent from OAuth 2.1.
  • The password grant: MUST NOT in RFC 9700, and absent from OAuth 2.1.
  • An access token in the access_token URL parameter (RFC 6750, section 2.3): MUST NOT in RFC 9700.
  • The PKCE plain method and wildcards in redirect_uri: removed in OAuth 2.1.
  • OAuth 1.0 (RFC 5849): replaced by RFC 6749 and incompatible with OAuth 2.0.

If a library’s documentation or an article cites RFC 6749, check it against RFC 9700: some of what was acceptable in 2012 is now forbidden. The current status of any RFC is on its rfc-editor.org/info page, which shows which document obsoletes or updates it.

How to read a standard

Requirements in RFCs are marked with the keywords of RFC 2119 and RFC 8174, which carry their special meaning only when written in capitals. MUST and MUST NOT are an absolute requirement or prohibition. SHOULD and SHOULD NOT are a recommendation that you may depart from only after weighing the consequences. MAY is truly optional. OAuth requirements are addressed to roles (the client, the authorization server, the resource server), so first look at whom a sentence applies to.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “OAuth and OIDC” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61