oauth2
БесплатноБез исполняемых скриптовНе проверенOAuth 2.0 authorization framework. Covers flows, tokens, and provider integration. Use for third-party authentication. USE WHEN: user mentions "OAuth"…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
OAuth 2.0 Core Knowledge
Deep Knowledge: Use
mcp__documentation__fetch_docswith technology:oauth2for comprehensive documentation.
Authorization Code Flow (Recommended)
1. User clicks "Login with Google"
2. Redirect to provider:
GET https://accounts.google.com/oauth/authorize
?client_id=xxx
&redirect_uri=https://app.com/callback
&response_type=code
&scope=openid email profile
&state=random_state
3. User authorizes, provider redirects:
GET https://app.com/callback?code=xxx&state=random_state
4. Backend exchanges code for tokens:
POST https://oauth2.googleapis.com/token
client_id=xxx
client_secret=xxx
code=xxx
grant_type=authorization_code
redirect_uri=https://app.com/callback
5. Receive tokens:
{ "access_token": "...", "refresh_token": "...", "id_token": "..." }
Implementation
// Step 1: Generate auth URL
function getAuthUrl(): string {
const params = new URLSearchParams({
client_id: process.env.GOOGLE_CLIENT_ID,
redirect_uri: `${process.env.APP_URL}/callback`,
response_type: 'code',
scope: 'openid email profile',
state: generateRandomState(),
});
return `https://accounts.google.com/oauth/authorize?${params}`;
}
// Step 2: Handle callback
async function handleCallback(code: string) {
const tokens = await exchangeCodeForTokens(code);
const userInfo = await getUserInfo(tokens.access_token);
const user = await findOrCreateUser(userInfo);
return generateSessionToken(user);
}
When NOT to Use This Skill
- Simple JWT authentication - Use
jwtskill for custom token-based auth - NextAuth.js integration - Use
nextauthskill for Next.js projects - Internal authentication - Use traditional username/password with JWT
- API-to-API communication - Use API keys or mTLS
Common Flows
| Flow | Use Case |
|---|---|
| Authorization Code | Web apps (server-side) |
| Authorization Code + PKCE | SPAs, mobile apps |
| Client Credentials | Machine-to-machine |
| Refresh Token | Long-lived sessions |
Anti-Patterns
| Anti-Pattern | Why It's Bad | Correct Approach |
|---|---|---|
| No state parameter | Vulnerable to CSRF attacks | Always generate and validate state |
| PKCE without S256 | Weak code challenge | Use S256 (SHA-256), not plain |
| Storing tokens in localStorage | XSS vulnerability | Use httpOnly cookies or secure storage |
| Ignoring provider errors | Silent failures | Handle all error codes properly |
| Hardcoded redirect URLs | Security risk | Use environment variables |
| No nonce validation | ID token replay attacks | Validate nonce for OpenID Connect |
Quick Troubleshooting
| Issue | Cause | Solution |
|---|---|---|
| "Invalid redirect_uri" | URL mismatch with provider | Exact match required, check protocol/trailing slash |
| "Invalid state" | CSRF token mismatch | Verify state cookie exists and matches |
| "Invalid code" | Code expired or used twice | Codes expire in ~10 minutes, can only be used once |
| "Invalid client" | Wrong client_id/secret | Verify credentials from provider console |
| CORS errors | Same-origin policy | Use backend proxy for token exchange |
| "Invalid grant" | Code verifier mismatch | Ensure code_verifier matches code_challenge |
PKCE Extension
// For SPAs - no client_secret needed
const codeVerifier = generateRandomString(64);
const codeChallenge = base64url(sha256(codeVerifier));
// Add to auth URL
params.set('code_challenge', codeChallenge);
params.set('code_challenge_method', 'S256');
// Include in token exchange
body.code_verifier = codeVerifier;
Production Readiness
Security Configuration
// Secure state parameter (CSRF protection)
import { randomBytes, createHash } from 'crypto';
function generateState(): string {
return randomBytes(32).toString('hex');
}
// Store state in httpOnly cookie before redirect
res.cookie('oauth_state', state, {
httpOnly: true,
secure: true,
sameSite: 'lax', // Required for OAuth redirects
maxAge: 10 * 60 * 1000, // 10 minutes
});
// Validate state on callback
function validateState(receivedState: string, storedState: string): void {
if (!receivedState || !storedState || receivedState !== storedState) {
throw new Error('Invalid state parameter - possible CSRF attack');
}
}
PKCE Implementation (Required for SPAs/Mobile)
// Generate PKCE parameters
function generatePKCE(): { verifier: string; challenge: string } {
const verifier = randomBytes(32)
.toString('base64url')
.replace(/[^a-zA-Z0-9]/g, '')
.substring(0, 64);
const challenge = createHash('sha256')
.update(verifier)
.digest('base64url');
return { verifier, challenge };
}
// Store verifier securely (server-side session or encrypted cookie)
const { verifier, challenge } = generatePKCE();
session.codeVerifier = verifier;
// Include in aut
Установить oauth2 в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditВложенные файлы
FAQ
Что делает скилл oauth2?
OAuth 2.0 authorization framework. Covers flows, tokens, and provider integration. Use for third-party authentication. USE WHEN: user mentions "OAuth", "Google login", "GitHub auth", "social login", "authorization code flow", "PKCE", asks about "third-party auth", "provider integration" DO NOT USE FOR: JWT tokens (use jwt skill), NextAuth.js (use nextauth skill), API keys, simple password auth
Как установить скилл oauth2?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл oauth2 запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic