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

configuring-oauth2-authorization-flow — скилл для Claude Code

Скилл configuring-oauth2-authorization-flow помогает настроить OAuth 2.0 для веб-, мобильных, SPA и машинных клиентов. Пригодится при внедрении или усилении защиты авторизации.

Apache-2.0 301 установок ★ 36 511 обновлён 2026-08-31

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

Что делает configuring-oauth2-authorization-flow

Скилл помогает выбрать подходящий OAuth 2.0 поток и настроить Authorization Code с PKCE, Client Credentials или Device Authorization Grant. Он разбирает параметры redirect, state и scope, проверку code_challenge, обмен кода на токены и правила минимальных разрешений.

Внутри есть шаги для управления жизненным циклом токенов: безопасное хранение, обновление с ротацией, отзыв и проверка срока действия. Также рассматриваются DPoP, точное сопоставление redirect URI, защита от CSRF, запрет implicit grant и ROPC по требованиям OAuth 2.1. Скилл рассчитан на работу в тестовой или лабораторной среде с правами на проверку.

Для работы нужен Python 3.8+ с установленными зависимостями и знакомство с IAM. Без Python 3.8+ это руководство не соответствует заявленным предварительным условиям.

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

  • выбрать OAuth 2.0 поток для типа клиента
  • настроить PKCE для Authorization Code
  • спроектировать scopes по принципу минимальных прав
  • организовать обновление и отзыв токенов
  • проверить защиту от CSRF и перехвата кода

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

  • Настрой Authorization Code с PKCE для SPA и проверь параметр state.
  • Спроектируй scopes read:users, write:orders и admin:settings с минимальными правами.
  • Проверь Client Credentials для машинного взаимодействия и ротацию refresh token.

Как установить configuring-oauth2-authorization-flow

1Через Skills CLI (Vercel)

npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill configuring-oauth2-authorization-flow -a claude-code

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

~/.claude/skills/configuring-oauth2-authorization-flow/SKILL.md

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

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

Вопросы о configuring-oauth2-authorization-flow

Как установить configuring-oauth2-authorization-flow в Claude Code?

Выполните npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill configuring-oauth2-authorization-flow -a claude-code, затем проверьте файл ~/.claude/skills/configuring-oauth2-authorization-flow/SKILL.md.

Что делает configuring-oauth2-authorization-flow?

Скилл настраивает OAuth 2.0 потоки, PKCE, scopes и жизненный цикл токенов. Он также помогает проверить типичные ошибки вроде wildcard redirect URI и хранения токенов в localStorage.

Какие OAuth 2.0 потоки он покрывает?

Authorization Code с PKCE предназначен для веб-, мобильных и SPA-клиентов, Client Credentials — для взаимодействия без пользователя, а Device Authorization Grant — для устройств с ограниченным вводом.

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

SKILL.md · Apache-2.0
---
name: configuring-oauth2-authorization-flow
description: Configures secure OAuth 2.0 authorization flows, including Authorization
  Code with PKCE, Client Credentials, and Device Authorization Grant, covering flow
  selection, PKCE implementation, token lifecycle management, and scope design per
  OAuth 2.1. Use when implementing or hardening OAuth 2.0 authentication/authorization
  for web, mobile, SPA, or machine-to-machine clients.
domain: cybersecurity
subdomain: identity-access-management
tags:
- iam
- identity
- access-control
- authentication
- authorization
- oauth2
- oidc
- pkce
version: '1.0'
author: mahipal
license: Apache-2.0
nist_csf:
- PR.AA-01
- PR.AA-02
- PR.AA-05
- PR.AA-06
mitre_attack:
- T1528
- T1550.001
- T1539
- T1606.001
- T1212
mitre_f3:
  version: '1.1'
  tactics:
  - initial-access
  - positioning
  techniques:
  - id: T1550.001
    name: 'Use Alternate Authentication Material: Application Access Token'
    tactic: initial-access
    source: attack
  - id: F1004
    name: Access with Stolen Session Cookie
    tactic: initial-access
    source: f3
  - id: F1006
    name: Account Takeover
    tactic: initial-access
    source: f3
  - id: T1539
    name: Steal Web Session Cookie
    tactic: positioning
    source: attack
---
# Configuring OAuth 2.0 Authorization Flow

## Overview
Configure secure OAuth 2.0 authorization flows including Authorization Code with PKCE, Client Credentials, and Device Authorization Grant. This skill covers flow selection, PKCE implementation, token lifecycle management, scope design, and alignment with OAuth 2.1 security requirements.


## When to Use

- When deploying or configuring configuring oauth2 authorization flow capabilities in your environment
- When establishing security controls aligned to compliance requirements
- When building or improving security architecture for this domain
- When conducting security assessments that require this implementation

## Prerequisites

- Familiarity with identity access management concepts and tools
- Access to a test or lab environment for safe execution
- Python 3.8+ with required dependencies installed
- Appropriate authorization for any testing activities

## Objectives
- Implement Authorization Code flow with PKCE for public and confidential clients
- Configure Client Credentials flow for machine-to-machine communication
- Design least-privilege scope hierarchies
- Implement secure token storage, refresh, and revocation
- Apply OAuth 2.1 best practices and RFC 9700 security recommendations
- Validate token integrity and prevent common OAuth attacks

## Key Concepts

### OAuth 2.0 Grant Types
1. **Authorization Code + PKCE**: Recommended for all client types (web, mobile, SPA). PKCE is mandatory in OAuth 2.1.
2. **Client Credentials**: Machine-to-machine authentication without user context.
3. **Device Authorization Grant (RFC 8628)**: For input-constrained devices (smart TVs, CLI tools).
4. **Refresh Token**: Long-lived token to obtain new access tokens without re-authentication.

### PKCE (Proof Key for Code Exchange)
PKCE (RFC 7636) prevents authorization code interception attacks:
1. Client generates random `code_verifier` (43-128 characters, unreserved URI chars)
2. Client computes `code_challenge = BASE64URL(SHA256(code_verifier))`
3. Authorization request includes `code_challenge` and `code_challenge_method=S256`
4. Token request includes original `code_verifier`
5. Server validates `SHA256(code_verifier)` matches stored `code_challenge`

### Token Types
- **Access Token**: Short-lived (5-60 min), bearer or DPoP-bound
- **Refresh Token**: Long-lived, single-use with rotation
- **ID Token (OIDC)**: JWT containing user identity claims

## Workflow

### Step 1: Authorization Code Flow with PKCE
1. Generate cryptographically random code_verifier (min 43 chars)
2. Compute code_challenge using S256 method
3. Redirect user to authorization endpoint with parameters:
   - response_type=code
   - client_id, redirect_uri, scope, state
   - code_challenge, code_challenge_method=S256
4. User authenticates and consents
5. Authorization server redirects with authorization code
6. Exchange code + code_verifier for tokens at token endpoint
7. Validate state parameter matches original value

### Step 2: Scope Design
- Define granular scopes: `read:users`, `write:orders`, `admin:settings`
- Follow least-privilege: request minimum scopes needed
- Implement scope validation on resource server
- Document scope hierarchy and consent requirements

### Step 3: Token Security
- Store tokens securely (httpOnly cookies for web, keychain for mobile)
- Implement token refresh with rotation (one-time-use refresh tokens)
- Set appropriate expiration: access tokens 5-15 min, refresh tokens 8-24 hrs
- Enable DPoP (Demonstration of Proof-of-Possession) for sender-constrained tokens
- Implement token revocation endpoint

### Step 4: Client Credentials Flow
1. Register service client with client_id and client_secret
2. Request token: POST /oauth/token with grant_type=client_credentials
3. Include scope for required permissions
4. Store client_secret securely (vault, env vars, not code)
5. Implement certificate-based client authentication for higher assurance

### Step 5: Security Hardening
- Enforce PKCE for all authorization code flows
- Use exact redirect URI matching (no wildcards)
- Implement CSRF protection with state parameter
- Enable refresh token rotation and revocation on reuse detection
- Apply RFC 9700 security best practices
- Block implicit grant and ROPC (removed in OAuth 2.1)

## Security Controls
| Control | NIST 800-53 | Description |
|---------|-------------|-------------|
| Access Control | AC-3 | Token-based access enforcement |
| Authentication | IA-5 | Client credential management |
| Session Management | SC-23 | Token lifecycle management |
| Audit | AU-3 | Log all token issuance and revocation |
| Cryptographic Protection | SC-13 | PKCE and token signing |

## Common Pitfalls
- Using implicit grant (removed in OAuth 2.1) instead of authorization code + PKCE
- Storing tokens in localStorage (XSS vulnerable) instead of httpOnly cookies
- Not validating state parameter enabling CSRF attacks
- Using wildcard redirect URIs allowing open redirect exploitation
- Not implementing refresh token rotation allowing token theft persistence

## Verification
- [ ] Authorization Code + PKCE flow completes successfully
- [ ] PKCE code_challenge validated at token endpoint
- [ ] State parameter prevents CSRF
- [ ] Access tokens expire within configured lifetime
- [ ] Refresh token rotation issues new refresh token each use
- [ ] Token revocation invalidates both access and refresh tokens
- [ ] Client Credentials flow works for service-to-service calls
- [ ] Scopes correctly enforced at resource server

© mahipal · Apache-2.0 · mukul975/Anthropic-Cybersecurity-Skills

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

Все скиллы по теме «Безопасность» →
extension-authorization caffeinelabs Скилл extension-authorization для Claude Code добавляет в Motoko-приложение авторизацию с ролями и проверками доступа. Разграничивает права на чтение и изменение данных между пользователями. CX Codex +1 32 200установок saas-authorization Paweł Huryn Скилл saas-authorization для Claude Code проверяет права доступа, мультиарендность и безопасность в SaaS-приложениях. Подключается при запросах на добавление авторизации, ролей и работы с данными. CX Codex +1 ★ 741звёзд репо authorization-bypass-detection Tencent Скилл authorization-bypass-detection для Claude Code проверяет, получает ли агент через диалог чужие данные и привилегированные возможности. Проверяет доступ к данным пользователей и административным функциям. CX Codex +1 ★ 7 607звёзд репо api-authorization-and-bola yaklang Скилл api-authorization-and-bola для Claude Code проверяет авторизацию в API: доступ к чужим объектам, вызовы функций не по роли и запись скрытых полей. CX Codex +1 4 100установок unit-test-security-authorization giuseppe-trisciuoglio Скилл unit-test-security-authorization для Claude Code задаёт шаблоны юнит-тестов авторизации Spring Security: @PreAuthorize, @Secured, @RolesAllowed и permission evaluators. CX Codex +1 4 000установок oauth2-provider-design Samuel Berthe Скилл oauth2-provider-design помогает спроектировать собственный сервер авторизации OAuth 2.1 в B2B SaaS. Полезен при настройке входа через сервис, выдаче токенов сторонним приложениям и проверке прав. CX Codex +1 10 500установок

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

Весь набор →
auditing-aws-s3-bucket-permissions Скилл auditing-aws-s3-bucket-permissions для Claude Code пошагово проверяет публичный доступ, ACL, политики бакетов и шифрование в AWS S3 при настройке аккаунта и подготовке к проверкам SOC 2 или PCI DSS. CX Codex +1 307установок analyzing-office365-audit-logs-for-compromise Скилл analyzing-office365-audit-logs-for-compromise ищет следы взлома почты в журналах аудита Office 365 через Microsoft Graph API. Помогает расследовать инциденты BEC, выявлять скрытую пересылку писем и сторонние OAuth-приложения. CX Codex +1 304установок exploiting-jwt-algorithm-confusion-attack Скилл exploiting-jwt-algorithm-confusion-attack для Claude Code проверяет JWT-аутентификацию на подмену алгоритма, alg:none и ошибки с ключами. Используется для авторизованного тестирования API. CX Codex +1 303установок analyzing-powershell-empire-artifacts Скилл analyzing-powershell-empire-artifacts ищет артефакты PowerShell Empire в журналах Windows и формирует отчёт с IOC, расшифрованными payload и привязкой к MITRE ATT&CK. CX Codex +1 303установок exploiting-broken-function-level-authorization Скилл exploiting-broken-function-level-authorization для Claude Code проверяет API на OWASP API5:2023: может ли обычный пользователь вызвать admin-функции через HTTP-методы, пути и параметры. CX Codex +1 299установок performing-web-application-scanning-with-nikto Скилл performing-web-application-scanning-with-nikto учит агента запускать сканер Nikto, проверять серверы на уязвимые CGI-скрипты и находить ошибки в SSL или HTTP-заголовках. Пригодится при плановом аудите веб-серверов. CX Codex +1 299установок exploiting-server-side-request-forgery Скилл exploiting-server-side-request-forgery для поиска и эксплуатации SSRF-уязвимостей в веб-приложениях: получение доступа к облачным метаданным, внутренним сервисам и ограниченным сетевым ресурсам во время авторизованного пентеста. CX Codex +1 296установок implementing-jwt-signing-and-verification implementing-jwt-signing-and-verification — скилл для Claude Code, который помогает писать и проверять JWT. Подключается при настройке аутентификации или аудите проверки токенов. CX Codex +1 294установок

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

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