---
name: oauth2-oidc-92b5173a78de
description: >-
  Assists with implementing OAuth 2.0 and OpenID Connect for secure authentication and
  authorization. Use when configuring authorization flows, validating tokens, implementing
  PKCE for public clients, setting up social login, or building secure token handling for
  SPAs, mobile apps, and APIs. Trigger words: oauth, oidc, openid connect, authorization
  code, pkce, jwt, access token, refresh token.
license: Apache-2.0
compatibility: "No special requirements"
metadata:
  author: terminal-skills
  version: "1.1.0"
  category: devops
  tags: "oauth2, oidc, authentication, authorization, jwt"
  repository: https://www.rfc-editor.org/rfc/rfc9700
---

# OAuth 2.0 / OpenID Connect

## Overview

OAuth 2.0 is the industry standard for API authorization, and OpenID Connect (OIDC) extends it for user authentication. Together they provide Authorization Code + PKCE for secure token exchange, JWT-based identity tokens, refresh token rotation, and integration with identity providers (Auth0, Okta, Keycloak, Google, Microsoft Entra ID) for social login and enterprise SSO.

## Instructions

Current baseline: RFC 9700 (OAuth 2.0 Security Best Current Practice, January 2025, BCP 240) updates RFC 6749; OAuth 2.1 is still an IETF draft (`draft-ietf-oauth-v2-1-16`), so cite RFC 9700 and RFC 7636 rather than "the OAuth 2.1 spec".

- When implementing authentication, use the Authorization Code flow with PKCE (`code_challenge_method=S256`, never `plain`). RFC 9700 makes PKCE mandatory for public clients (SPAs, mobile, CLI) and recommended for confidential clients. Do not use the Implicit flow (`response_type=token`; RFC 9700 says clients SHOULD NOT) or the Resource Owner Password flow (MUST NOT be used).
- Send a random `state` (or rely on PKCE) to bind the response to the request, and a `nonce` for OIDC; check both on return. Compare redirect URIs by exact string match, register each one, and use `https` (loopback or a claimed scheme for native apps, RFC 8252). Check the `iss` value in the authorization response (RFC 9207) when you talk to more than one authorization server.
- Treat the ID token as proof of login for the client only. Never send it to an API as a bearer credential, and never read user identity from an access token you do not own.
- When validating tokens on the API side, verify the JWT signature against the provider's JWKS (cached, refetched on an unknown `kid`), pin the accepted algorithms, and check `exp`, `iss` and `aud` (and `scope`). JWT access tokens follow RFC 9068 (header `typ: at+jwt`). If the provider issues opaque tokens, use introspection (RFC 7662) instead.
- When storing tokens in web apps, prefer a backend-for-frontend: the server keeps tokens and the browser holds only an `httpOnly`, `Secure`, `SameSite=Lax` session cookie. Avoid localStorage, which any XSS can read.
- When managing token lifecycle, use short-lived access tokens (5-15 minutes). Refresh tokens for public clients must be rotated (single-use, a new one with each refresh) or sender-constrained; reuse of an old one should revoke the whole family.
- When integrating a provider, read endpoints from `/.well-known/openid-configuration` (OIDC discovery) or RFC 8414 metadata instead of hardcoding them.
  Check what the provider supports before relying on it; Google's document, for example, has no `end_session_endpoint`:

  ```console
  $ curl -s https://accounts.google.com/.well-known/openid-configuration | jq '{issuer, jwks_uri, code_challenge_methods_supported}'
  {"issuer":"https://accounts.google.com","jwks_uri":"https://www.googleapis.com/oauth2/v3/certs","code_challenge_methods_supported":["plain","S256"]}
  ```
- When implementing logout, revoke the refresh token (RFC 7009), clear the local session, then redirect to the provider's `end_session_endpoint` with `id_token_hint` and a registered `post_logout_redirect_uri` (OIDC RP-Initiated Logout 1.0).

## Examples

### Example 1: Add social login to a Next.js app with PKCE

**User request:** "Implement Google and GitHub login for my Next.js app using OAuth 2.0"

**Actions:**
1. Register the app with Google (OIDC) and GitHub (plain OAuth 2.0, no ID token) and configure client IDs and redirect URIs
2. Implement the Authorization Code + PKCE flow with state validation (and nonce for OIDC)
3. Exchange the code for tokens; for Google validate the ID token claims (`iss`, `aud`, `exp`, `nonce`), for GitHub read the user from its API with the access token
4. Store the session in httpOnly cookies with refresh token rotation

**Output:** A Next.js app with secure social login via Google and GitHub, PKCE-protected token exchange, and httpOnly cookie sessions.

The authorization request (Node.js; both lengths verified at 43 characters):

```javascript
import { randomBytes, createHash } from 'node:crypto';

const verifier = randomBytes(32).toString('base64url');          // keep server-side, per login
const challenge = createHash('sha256').update(verifier).digest('base64url');
const url = new URL('https://accounts.google.com/o/oauth2/v2/auth');
url.search = new URLSearchParams({
  response_type: 'code',
  client_id: process.env.GOOGLE_CLIENT_ID,
  redirect_uri: 'https://app.shopline.dev/auth/callback/google',
  scope: 'openid email profile',
  state: randomBytes(16).toString('base64url'),
  nonce: randomBytes(16).toString('base64url'),
  code_challenge: challenge,
  code_challenge_method: 'S256',
});
// redirect the browser to url; on the callback, check state, then POST code + code_verifier to the token endpoint
```

### Example 2: Secure a REST API with JWT validation

**User request:** "Add OAuth 2.0 token validation to my API endpoints"

**Actions:**
1. Fetch the provider's JWKS from the discovery endpoint
2. Create middleware that validates the access token signature, expiration, issuer, and audience
3. Extract user claims and custom scopes from the validated token
4. Return 401 for invalid tokens and 403 for insufficient scopes

**Output:** An API with JWT-based authorization that validates tokens against the provider's JWKS and enforces scope-based access control.

Verified with `jose` 6.2.13 (Node.js, ESM):

```javascript
import { createRemoteJWKSet, jwtVerify } from 'jose';

const jwks = createRemoteJWKSet(new URL('https://id.shopline.dev/.well-known/jwks.json'));

export async function requireAuth(req, res, next) {
  const token = req.headers.authorization?.replace(/^Bearer /, '');
  if (!token) return res.status(401).end();
  try {
    const { payload } = await jwtVerify(token, jwks, {
      issuer: 'https://id.shopline.dev/',
      audience: 'https://api.shopline.dev',
      algorithms: ['RS256'],
    });
    if (!String(payload.scope).split(' ').includes('orders:read')) return res.status(403).end();
    req.user = payload;
    next();
  } catch {
    res.status(401).end();   // bad signature, expired, wrong iss/aud
  }
}
```

A token minted for a different audience fails with `ERR_JWT_CLAIM_VALIDATION_FAILED`, so the API returns 401 rather than accepting it.

## Guidelines

- Use Authorization Code + PKCE (S256) for every client type; add `state` and `nonce`.
- Never accept a token you have not validated on the server: signature, `exp`, `iss`, `aud`, allowed algorithm. Do not accept `alg: none` or let the token header pick the algorithm.
- Keep tokens out of localStorage and URLs; use `httpOnly`, `Secure`, `SameSite=Lax` cookies or a backend-for-frontend.
- Rotate refresh tokens (single-use) and revoke on logout.
- Use discovery rather than hardcoded endpoints, and exact-match registered redirect URIs.
- Request the minimum scopes: `openid email` for login, not every scope available.
- Do not write your own authorization server unless you must; use a maintained one (Keycloak, Auth0, Okta, Entra ID) and a maintained client library.
- Implement full logout: revoke the refresh token, clear the session, redirect to the provider's logout endpoint.


---
Source attribution: terminal-skills
Original project: https://github.com/TerminalSkills/skills/blob/8a9852d489f274538be9bf1c9121aeb403750b1c/skills/oauth2-oidc/SKILL.md
License: Apache-2.0
License information: https://www.apache.org/licenses/LICENSE-2.0
Original upstream instructions; downloaded from Dave AI.

## Upstream license notice

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by the Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding any notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   Copyright 2025 Terminal Skills

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.



# Dave AI resource metadata

Creator / publisher: terminal-skills
Original project: https://github.com/TerminalSkills/skills/blob/8a9852d489f274538be9bf1c9121aeb403750b1c/skills/oauth2-oidc/SKILL.md
Attribution basis: Source repository record

Fields of work: Development & Engineering, Product Management
Roles: Backend Developer, DevOps / SRE, Full-Stack Developer, Security Engineer, Product Manager
Specialties: Backend, API, Cross Platform
Tools: Auth0, Okta, Keycloak, Google, Azure Ad
Country applicability: Country not specified
Classification basis: Source category, role and specialization labels
Instruction SHA-256: 083e7e8eff457ca44ecd26d9689ad80895dc936b87930561039dcc23d48b43e5
