oauth2-oidc-implementer
Implements OAuth 2.0 and OpenID Connect authentication flows with secure token handling and provider integration. Use when users request "OAuth setup", "OIDC implementation", "social login", "SSO integration", or "authentication flow".
What this skill does
# OAuth 2.0 & OIDC Implementer
Implement secure authentication with OAuth 2.0 and OpenID Connect.
## Core Workflow
1. **Choose flow**: Authorization Code, PKCE, Client Credentials
2. **Configure provider**: Set up OAuth/OIDC provider
3. **Implement flow**: Handle redirects and tokens
4. **Secure tokens**: Storage and refresh
5. **Add providers**: Multiple identity providers
6. **Handle sessions**: Manage authenticated state
## OAuth 2.0 Flows Overview
```
┌─────────────────────────────────────────────────────────────┐
│ OAuth 2.0 Flows │
├─────────────────────────────────────────────────────────────┤
│ Authorization Code + PKCE │ Web/Mobile apps (recommended) │
│ Client Credentials │ Machine-to-machine │
│ Device Code │ TV/IoT devices │
│ Implicit (deprecated) │ Do not use │
└─────────────────────────────────────────────────────────────┘
```
## Authorization Code Flow with PKCE
### Server Implementation (Next.js)
```typescript
// lib/auth/oauth.ts
import { randomBytes, createHash } from 'crypto';
interface OAuthConfig {
clientId: string;
clientSecret: string;
authorizationUrl: string;
tokenUrl: string;
redirectUri: string;
scopes: string[];
}
const config: OAuthConfig = {
clientId: process.env.OAUTH_CLIENT_ID!,
clientSecret: process.env.OAUTH_CLIENT_SECRET!,
authorizationUrl: 'https://provider.com/oauth/authorize',
tokenUrl: 'https://provider.com/oauth/token',
redirectUri: process.env.OAUTH_REDIRECT_URI!,
scopes: ['openid', 'profile', 'email'],
};
// Generate PKCE challenge
function generateCodeVerifier(): string {
return randomBytes(32).toString('base64url');
}
function generateCodeChallenge(verifier: string): string {
return createHash('sha256').update(verifier).digest('base64url');
}
// Generate state for CSRF protection
function generateState(): string {
return randomBytes(16).toString('hex');
}
export function getAuthorizationUrl(): {
url: string;
state: string;
codeVerifier: string;
} {
const state = generateState();
const codeVerifier = generateCodeVerifier();
const codeChallenge = generateCodeChallenge(codeVerifier);
const params = new URLSearchParams({
client_id: config.clientId,
redirect_uri: config.redirectUri,
response_type: 'code',
scope: config.scopes.join(' '),
state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});
return {
url: `${config.authorizationUrl}?${params}`,
state,
codeVerifier,
};
}
export async function exchangeCodeForTokens(
code: string,
codeVerifier: string
): Promise<TokenResponse> {
const response = await fetch(config.tokenUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: config.clientId,
client_secret: config.clientSecret,
code,
redirect_uri: config.redirectUri,
code_verifier: codeVerifier,
}),
});
if (!response.ok) {
const error = await response.json();
throw new OAuthError(error.error_description || 'Token exchange failed');
}
return response.json();
}
interface TokenResponse {
access_token: string;
token_type: string;
expires_in: number;
refresh_token?: string;
id_token?: string;
scope: string;
}
```
### Login Route
```typescript
// app/api/auth/login/route.ts
import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { getAuthorizationUrl } from '@/lib/auth/oauth';
export async function GET() {
const { url, state, codeVerifier } = getAuthorizationUrl();
// Store state and verifier in secure, httpOnly cookies
const cookieStore = cookies();
cookieStore.set('oauth_state', state, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 600, // 10 minutes
path: '/',
});
cookieStore.set('code_verifier', codeVerifier, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 600,
path: '/',
});
return NextResponse.redirect(url);
}
```
### Callback Route
```typescript
// app/api/auth/callback/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { exchangeCodeForTokens } from '@/lib/auth/oauth';
import { createSession } from '@/lib/auth/session';
export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const code = searchParams.get('code');
const state = searchParams.get('state');
const error = searchParams.get('error');
// Handle OAuth errors
if (error) {
const errorDescription = searchParams.get('error_description');
return NextResponse.redirect(
new URL(`/login?error=${encodeURIComponent(errorDescription || error)}`, request.url)
);
}
// Validate state
const cookieStore = cookies();
const storedState = cookieStore.get('oauth_state')?.value;
const codeVerifier = cookieStore.get('code_verifier')?.value;
if (!state || state !== storedState) {
return NextResponse.redirect(
new URL('/login?error=invalid_state', request.url)
);
}
if (!code || !codeVerifier) {
return NextResponse.redirect(
new URL('/login?error=missing_code', request.url)
);
}
try {
// Exchange code for tokens
const tokens = await exchangeCodeForTokens(code, codeVerifier);
// Create session with tokens
await createSession(tokens);
// Clear OAuth cookies
cookieStore.delete('oauth_state');
cookieStore.delete('code_verifier');
return NextResponse.redirect(new URL('/dashboard', request.url));
} catch (error) {
console.error('OAuth callback error:', error);
return NextResponse.redirect(
new URL('/login?error=authentication_failed', request.url)
);
}
}
```
## OpenID Connect Integration
### OIDC Discovery
```typescript
// lib/auth/oidc.ts
interface OIDCConfig {
issuer: string;
authorization_endpoint: string;
token_endpoint: string;
userinfo_endpoint: string;
jwks_uri: string;
scopes_supported: string[];
response_types_supported: string[];
}
let cachedConfig: OIDCConfig | null = null;
export async function discoverOIDCConfig(issuer: string): Promise<OIDCConfig> {
if (cachedConfig) return cachedConfig;
const response = await fetch(`${issuer}/.well-known/openid-configuration`);
if (!response.ok) {
throw new Error('Failed to fetch OIDC configuration');
}
cachedConfig = await response.json();
return cachedConfig;
}
```
### ID Token Validation
```typescript
// lib/auth/jwt.ts
import { createRemoteJWKSet, jwtVerify } from 'jose';
import { discoverOIDCConfig } from './oidc';
interface IDTokenClaims {
iss: string;
sub: string;
aud: string | string[];
exp: number;
iat: number;
nonce?: string;
email?: string;
email_verified?: boolean;
name?: string;
picture?: string;
}
let jwks: ReturnType<typeof createRemoteJWKSet> | null = null;
export async function verifyIdToken(
idToken: string,
expectedNonce?: string
): Promise<IDTokenClaims> {
const config = await discoverOIDCConfig(process.env.OIDC_ISSUER!);
if (!jwks) {
jwks = createRemoteJWKSet(new URL(config.jwks_uri));
}
const { payload } = await jwtVerify(idToken, jwks, {
issuer: config.issuer,
audience: process.env.OAUTH_CLIENT_ID!,
});
// Verify nonce if provided (for implicit/hybrid flows)
if (expectedNonce && payload.nonce !== expectedNonce) {
throw new Error('Invalid nonce');
}
return payload as IDTokenClaims;
}
```
### User Info Endpoint
```typescript
// lib/auth/userinfo.ts
interface UserInfo {
sub: string;
email?: string;
email_verified?: boolean;
name?: string;
given_name?: string;
family_name?: string;
picture?: string;
locale?: string;
}
export aRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.