К основному содержанию
скилл CX Codex

auth0-authentication — скилл для Claude Code: правила Auth0

Скилл задаёт агенту правила работы с Auth0: потоки авторизации, Actions, проверка токенов и защита редиректов.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add Mindrally/skills --skill auth0-authentication -a claude-code
Открыть на GitHub

Что делает auth0-authentication

Скилл превращает ассистента в инструкцию по Auth0: он подсказывает, какой поток выбрать, как хранить секреты и где обычно ломается вход. Внутри — разделы про переменные окружения, Authorization Code Flow с PKCE для SPA и нативных приложений, серверный поток на express-openid-connect, Actions вместо устаревших Rules, работу с access- и refresh-токенами, MFA и обработку ошибок.

Отдельный блок — чего не делать: не хранить токены в localStorage без учёта XSS, не валидировать токены только на клиенте, не хардкодить client_secret во фронтенде, не оставлять logout без завершения сессии на стороне Auth0. Про implicit flow сказано прямо: он устарел.

Для работы понадобятся AUTH0_DOMAIN, AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET, AUTH0_AUDIENCE, AUTH0_CALLBACK_URL и AUTH0_LOGOUT_URL в переменных окружения — скилл требует держать их вне кода. Секреты для Actions хранятся в Action Secrets. Внешние вызовы внутри Action тормозят вход, поэтому их советуют минимизировать и ставить короткие таймауты.

Какие задачи решает

  • выбрать поток авторизации под SPA, нативное или серверное приложение
  • настроить проверку access-токена и требуемых scope на бэкенде
  • переписать Rules на Actions и не сломать логин
  • закрыть дыры в редиректах, сессиях и хранении токенов
  • добавить MFA для чувствительных операций

Примеры запросов агенту

  • Проверь мою настройку Auth0 для SPA: нужен ли здесь PKCE и где я храню токены
  • Перепиши это Auth0 Rule в Action и убери лишние внешние вызовы
  • Настрой проверку JWT и scope read:messages для Express-роутов

Как установить auth0-authentication

1Через Skills CLI (Vercel)

npx skills add Mindrally/skills --skill auth0-authentication -a claude-code

2Вручную: положить файлы

~/.claude/skills/auth0-authentication/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/auth0-authentication/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о auth0-authentication

Как установить auth0-authentication в Claude?

Выполните npx skills add Mindrally/skills --skill auth0-authentication -a claude-code. После этого файл скилла лежит в ~/.claude/skills/auth0-authentication/SKILL.md.

Что делает auth0-authentication?

Даёт агенту набор правил по внедрению Auth0: потоки авторизации, Actions, управление токенами, MFA и типичные ошибки безопасности.

Нужен ли Auth0 MCP-сервер?

Скилл упоминает MCP-сервер Auth0 для работы с тенантом на естественном языке: npx @auth0/auth0-mcp-server init --client cursor. Для самих правил он не обязателен.

Исходный текст

SKILL.md · Apache-2.0
---
name: auth0-authentication
description: Guidelines for implementing Auth0 authentication with best practices for security, rules, actions, and SDK integration
metadata:
  maintainer: Mindrally
  source: https://github.com/Mindrally/skills
---

# Auth0 Authentication

You are an expert in Auth0 authentication implementation. Follow these guidelines when working with Auth0 in any project.

## Core Principles

- Always use HTTPS for all Auth0 communications and callbacks
- Store sensitive configuration (client secrets, API keys) in environment variables, never in code
- Implement proper error handling for all authentication flows
- Follow the principle of least privilege for scopes and permissions

## Environment Variables

```bash
# Required Auth0 Configuration
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secret
AUTH0_AUDIENCE=your-api-audience
AUTH0_CALLBACK_URL=https://your-app.com/callback
AUTH0_LOGOUT_URL=https://your-app.com
```

## Authentication Flows

### Authorization Code Flow with PKCE (Recommended for SPAs and Native Apps)

Always use PKCE for public clients:

```javascript
import { Auth0Client } from '@auth0/auth0-spa-js';

const auth0 = new Auth0Client({
  domain: process.env.AUTH0_DOMAIN,
  clientId: process.env.AUTH0_CLIENT_ID,
  authorizationParams: {
    redirect_uri: window.location.origin,
    audience: process.env.AUTH0_AUDIENCE,
  },
  cacheLocation: 'localstorage', // Use 'memory' for higher security
  useRefreshTokens: true,
});
```

### Authorization Code Flow (Server-Side Applications)

```javascript
// Express.js example
const { auth } = require('express-openid-connect');

app.use(
  auth({
    authRequired: false,
    auth0Logout: true,
    secret: process.env.AUTH0_SECRET,
    baseURL: process.env.BASE_URL,
    clientID: process.env.AUTH0_CLIENT_ID,
    issuerBaseURL: `https://${process.env.AUTH0_DOMAIN}`,
  })
);
```

## Auth0 Actions Best Practices

Actions have replaced Rules. Follow these guidelines:

### Action Structure

```javascript
exports.onExecutePostLogin = async (event, api) => {
  // 1. Early returns for efficiency
  if (!event.user.email_verified) {
    api.access.deny('Please verify your email before logging in.');
    return;
  }

  // 2. Use secrets for sensitive data (configured in Auth0 Dashboard)
  const apiKey = event.secrets.EXTERNAL_API_KEY;

  // 3. Minimize external calls - they affect login latency
  // 4. Never log sensitive information
  console.log(`User logged in: ${event.user.user_id}`);

  // 5. Add custom claims sparingly
  api.idToken.setCustomClaim('https://myapp.com/roles', event.authorization?.roles || []);
  api.accessToken.setCustomClaim('https://myapp.com/roles', event.authorization?.roles || []);
};
```

### Action Security Rules

- Store secrets in Action Secrets, never hardcode them
- Limit the data sent to external services - never send the entire event object
- Use short timeouts for external API calls (default 20-second limit)
- Implement proper error handling to avoid authentication failures

## Token Management

### Access Token Best Practices

```javascript
// Always validate tokens server-side
const { auth, requiredScopes } = require('express-oauth2-jwt-bearer');

const checkJwt = auth({
  audience: process.env.AUTH0_AUDIENCE,
  issuerBaseURL: `https://${process.env.AUTH0_DOMAIN}/`,
  tokenSigningAlg: 'RS256',
});

// Require specific scopes
const checkScopes = requiredScopes('read:messages');

app.get('/api/private-scoped', checkJwt, checkScopes, (req, res) => {
  res.json({ message: 'Protected resource' });
});
```

### Refresh Token Configuration

- Enable refresh token rotation
- Set appropriate token lifetimes (access tokens: 1 hour max, refresh tokens: based on risk)
- Implement automatic token refresh in your client

## Security Best Practices

### CSRF Protection

```javascript
// State parameter is automatically handled by Auth0 SDKs
// For custom implementations, always validate the state parameter
const state = generateSecureRandomString();
sessionStorage.setItem('auth0_state', state);
```

### Redirect URI Security

- Whitelist all redirect URIs in Auth0 Dashboard
- Use exact string matching for redirect URIs
- Never use wildcard redirect URIs in production

### Session Management

```javascript
// Implement session timeouts
const sessionConfig = {
  absoluteDuration: 86400, // 24 hours
  inactivityDuration: 3600, // 1 hour of inactivity
};
```

## Multi-Factor Authentication

```javascript
// Enforce MFA for sensitive operations
exports.onExecutePostLogin = async (event, api) => {
  // Check if MFA has been completed
  if (!event.authentication?.methods?.find(m => m.name === 'mfa')) {
    // Trigger MFA challenge
    api.authentication.challengeWithAny([
      { type: 'otp' },
      { type: 'push-notification' },
    ]);
  }
};
```

## Error Handling

```javascript
try {
  await auth0.loginWithRedirect();
} catch (error) {
  if (error.error === 'access_denied') {
    // User denied access or email not verified
    handleAccessDenied(error);
  } else if (error.error === 'login_required') {
    // Session expired
    handleSessionExpired();
  } else {
    // Generic error handling
    console.error('Authentication error:', error.message);
    showUserFriendlyError();
  }
}
```

## MCP Integration

Auth0 provides an MCP server for AI-assisted development:

```bash
# Initialize Auth0 MCP server for Cursor
npx @auth0/auth0-mcp-server init --client cursor
```

This enables natural language Auth0 management operations within your IDE.

## Testing

- Use Auth0's test users for development
- Implement integration tests for authentication flows
- Test token expiration and refresh scenarios
- Verify MFA flows in staging environments

## Common Anti-Patterns to Avoid

1. Storing tokens in localStorage without considering XSS risks
2. Not validating tokens on the server side
3. Using the implicit flow (deprecated)
4. Hardcoding client secrets in frontend code
5. Not implementing proper logout (both local and Auth0 session)
6. Ignoring token expiration in API calls
7. Storing too much data in user metadata

© Mindrally · Apache-2.0 · Mindrally/skills

Похожие скиллы

Всё по теме «Безопасность» →
auth0 Auth0 Помогает настроить авторизацию пользователей, защиту API и токены в приложении. Пригодится при настройке входа без пароля, MFA или миграции с других сервисов. CX Codex +1 5 200установок api-authentication secondsky Скилл для ИИ-агента, который помогает писать аутентификацию в API: JWT, OAuth 2.0, API-ключи, сессии и защитные заголовки. CX Codex +1 533установок catalyst-authentication catalystbyzoho Помогает настроить вход, регистрацию и OAuth-подключения в Zoho Catalyst. Предупреждает о несовпадении ZAID между средами и ошибках локального запуска. CX Codex +1 999установок authentication-setup akillness Помогает выбрать способ аутентификации для веб-приложения или API и разложить её по границам: что берёт провайдер, что остаётся в приложении. CX Codex +1 368установок authbypass-authentication-flaws yaklang Скилл содержит сценарии тестирования механизмов аутентификации на уязвимости. Он помогает искать ошибки входа, сброса пароля, обхода 2FA и защиты от перебора. CX Codex +1 3 800установок authentication codewithmukesh Скилл для ИИ-агента, который подсказывает, как правильно настроить аутентификацию и авторизацию в ASP.NET Core: JWT, OIDC, Identity, политики. CX Codex +1 2 800установок

Из того же набора168

jax-best-practices Скилл задаёт агенту правила работы с JAX: чистые функции, jit, vmap, grad и профилирование. Пригодится, если вы пишете численный код или обучаете модели на JAX. CX Codex +1 704установок koa-typescript Задаёт агенту правила разработки API на Koa.js и TypeScript: слоистая модель middleware, async/await, структура проекта. CX Codex +1 704установок aws-development Скилл задаёт агенту правила разработки на AWS: Lambda, CDK, SAM, DynamoDB, IAM и serverless-архитектура через Infrastructure as Code. CX Codex +1 701установок prisma-development Задаёт агенту правила работы с Prisma ORM и TypeScript: схема, миграции, транзакции, обработка ошибок. Пригодится, когда в проекте есть Prisma. CX Codex +1 698установок supabase-development Задаёт агенту порядок работы с Supabase: схема базы, RLS-политики, авторизация, realtime-подписки и Edge Functions. CX Codex +1 699установок monorepo Скилл задаёт агенту набор правил для монорепозиториев на TypeScript, React, Next.js и Expo с Turbo. Пригодится, когда в одном репозитории живут несколько приложений и общих пакетов. CX Codex +1 694установок meta-prompt Скилл с набором мета-промптов: критикует ответы модели, разбирает ход решения и ставит оценку. Пригодится, когда нужно проверить качество ответа агента. CX Codex +1 691установок cloudflare-development Скилл с правилами разработки на edge-платформе Cloudflare: Workers, Pages, KV, D1, R2 и Durable Objects. Пригодится, когда агент пишет код для воркеров или настраивает wrangler.toml. CX Codex +1 689установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой