Skip to main content
ClaudeWave
Skill171 estrellas del repoactualizado 27d ago

oauth-2-0-setup

Implement OAuth 2.0 authentication flows including authorization code with PKCE, client credentials, and device code for secure API integration. Use when the user requests oauth 2 0 setup or provides relevant inputs for this workflow.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/seb1n/awesome-ai-agent-skills /tmp/oauth-2-0-setup && cp -r /tmp/oauth-2-0-setup/api-and-integration/oauth-2-0-setup ~/.claude/skills/oauth-2-0-setup
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# OAuth 2.0 Setup

This skill enables an AI agent to implement OAuth 2.0 authentication for API integrations. The agent selects the appropriate grant type for the use case—authorization code with PKCE for user-facing apps, client credentials for machine-to-machine auth, and device code for input-limited devices. It handles token storage, refresh token rotation, CSRF protection via the state parameter, and secure credential management throughout the flow.

## Workflow

1. **Select the appropriate grant type:** Choose the OAuth 2.0 flow based on the client type. Use authorization code with PKCE for web and mobile apps where a user is present—PKCE replaces the client secret and prevents authorization code interception attacks. Use client credentials for server-to-server communication with no user context. Use device code flow for CLI tools or smart TVs where browser-based login isn't possible. Implicit flow is deprecated and should not be used.

2. **Register the application with the provider:** Create an OAuth application in the provider's developer console (Google, GitHub, Auth0, etc.). Configure the redirect URI precisely—mismatched URIs are the most common setup error. For PKCE flows, mark the application as a public client. Record the client ID, client secret (if applicable), authorization endpoint, token endpoint, and scopes.

3. **Implement the authorization request:** Construct the authorization URL with the required parameters: `client_id`, `redirect_uri`, `response_type=code`, `scope`, and a cryptographically random `state` parameter for CSRF protection. For PKCE, generate a random `code_verifier` (43-128 characters), derive the `code_challenge` using SHA-256, and include both `code_challenge` and `code_challenge_method=S256` in the request. Store the state and code_verifier in the session.

4. **Handle the callback and exchange tokens:** When the provider redirects back with the authorization code, first verify the `state` parameter matches what was stored in the session. Then exchange the code for tokens by POSTing to the token endpoint with `grant_type=authorization_code`, the authorization code, `redirect_uri`, `client_id`, and the `code_verifier` (for PKCE). Parse the response for `access_token`, `refresh_token`, `expires_in`, and `token_type`.

5. **Store tokens securely:** Never store tokens in localStorage (XSS vulnerable) or URL parameters (logged in server access logs). Use HTTP-only secure cookies for web apps, the system keychain for desktop apps, and encrypted storage for mobile apps. Store refresh tokens server-side when possible. Record token expiration timestamps so you can proactively refresh before expiry.

6. **Implement token refresh and rotation:** Before each API call, check if the access token is expired or about to expire (within a 60-second window). If so, use the refresh token to get a new access token. Handle refresh token rotation—when the provider issues a new refresh token alongside the new access token, store the new refresh token and invalidate the old one. If refresh fails with an invalid_grant error, the user must re-authenticate.

## Supported Technologies

- **Providers:** Auth0, Google, GitHub, Microsoft Entra ID, Okta, AWS Cognito, Keycloak
- **Server frameworks:** Express.js, FastAPI, Django, Spring Security, ASP.NET Core
- **Libraries:** passport.js (Node.js), authlib (Python), oauthlib (Python), Spring Security OAuth
- **Token formats:** JWT (self-contained), opaque tokens (require introspection)
- **Standards:** RFC 6749 (OAuth 2.0), RFC 7636 (PKCE), RFC 8628 (Device Code), RFC 9449 (DPoP)

## Usage

Provide the agent with the OAuth provider, the type of application (web app, SPA, CLI, server-to-server), and the required scopes. The agent will select the correct grant type and produce a complete implementation including the authorization flow, token exchange, secure storage, and refresh logic.

## Examples

### Example 1: Authorization Code Flow with PKCE (Node.js/Express)

```javascript
const express = require("express");
const crypto = require("crypto");
const session = require("express-session");

const app = express();
app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  cookie: { secure: true, httpOnly: true, sameSite: "lax", maxAge: 3600000 },
}));

const OAUTH_CONFIG = {
  clientId: process.env.OAUTH_CLIENT_ID,
  authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
  tokenEndpoint: "https://oauth2.googleapis.com/token",
  redirectUri: "https://myapp.com/auth/callback",
  scopes: ["openid", "email", "profile"],
};

// Generate PKCE code verifier and challenge
function generatePKCE() {
  const verifier = crypto.randomBytes(32).toString("base64url");
  const challenge = crypto
    .createHash("sha256")
    .update(verifier)
    .digest("base64url");
  return { verifier, challenge };
}

// Step 1: Start authorization — redirect user to provider
app.get("/auth/login", (req, res) => {
  const state = crypto.randomBytes(16).toString("hex");
  const { verifier, challenge } = generatePKCE();

  // Store in session for verification on callback
  req.session.oauthState = state;
  req.session.codeVerifier = verifier;

  const params = new URLSearchParams({
    client_id: OAUTH_CONFIG.clientId,
    redirect_uri: OAUTH_CONFIG.redirectUri,
    response_type: "code",
    scope: OAUTH_CONFIG.scopes.join(" "),
    state: state,
    code_challenge: challenge,
    code_challenge_method: "S256",
    access_type: "offline",  // Request refresh token
    prompt: "consent",
  });

  res.redirect(`${OAUTH_CONFIG.authorizationEndpoint}?${params}`);
});

// Step 2: Handle callback — verify state and exchange code for tokens
app.get("/auth/callback", async (req, res) => {
  const { code, state, error } = req.query;

  if (error) {
    console.error(`OAuth error: ${error}`);
    return res.redirect("/auth/error");
  }

  // CSRF protection: verify state matches
  if (state !== req.session.oaut
agent-evaluationSkill

Design reproducible evaluations for AI agents with representative task sets, explicit rubrics, appropriate graders, baselines, regression gates, and failure analysis. Use when defining agent quality, comparing prompts or models, validating a release, measuring tool-use reliability, investigating regressions, or deciding whether an agent is ready for production.

agent-observabilitySkill

Design privacy-aware observability for AI agents using traces, spans, structured events, metrics, cost attribution, dashboards, alerts, and investigation workflows. Use when instrumenting an agent, debugging intermittent tool or model failures, defining service-level objectives, analyzing latency or spend, auditing agent decisions, or preparing production monitoring.

human-in-the-loopSkill

Design and verify auditable human oversight, approval gates, escalation paths, and safe state transitions for AI agent workflows. Use when deciding which agent actions require review, adding approve/reject or dual-control flows, preventing unauthorized autonomous effects, creating decision records, reducing rubber-stamping, or recovering safely from rejected, expired, or failed actions.

mcp-server-buildingSkill

Design, implement, harden, and verify Model Context Protocol (MCP) servers with precise tool contracts, least-privilege authorization, safe transports, structured errors, and interoperability tests. Use when creating a new MCP server, exposing an API or data source through MCP, reviewing an MCP server design, adding or revising MCP tools, or preparing an MCP server for production.

multi-agent-orchestrationSkill

Design and operate bounded multi-agent workflows with task decomposition, dependency graphs, ownership, handoff contracts, shared-state controls, approvals, recovery, and synthesis. Use when a task contains genuinely independent workstreams, specialized roles, parallel research or implementation, reviewer-worker loops, or coordination problems that one agent should not execute sequentially.

tool-schema-designSkill

Design and validate model-facing tool definitions with clear names, action-oriented descriptions, bounded JSON Schema parameters, explicit side effects, safe defaults, idempotency, errors, and realistic tests. Use when creating function-calling tools, MCP tools, agent actions, structured tool inputs, or when a model selects the wrong tool, invents arguments, or causes unsafe side effects.

agent-red-teamingSkill

Plan, execute, document, and retest authorized security assessments of AI agents and multi-agent workflows using safe adversarial cases, synthetic identities, canaries, and evidence-based findings. Use when defining red-team rules of engagement, assessing prompt injection or excessive agency, testing tool and identity boundaries, evaluating memory or cross-agent attacks, scoring a campaign, or verifying remediation in an approved environment.

prompt-injection-defenseSkill

Threat-model and harden AI agents, RAG systems, assistants, and tool-using workflows against direct, indirect, stored, cross-agent, and multimodal prompt injection. Use when reviewing an agent architecture, isolating untrusted content, constraining tools and egress, protecting secrets, adding injection-focused tests, investigating a suspected injection incident, or documenting residual prompt-injection risk.