jpskill.com
🛠️ 開発・MCP コミュニティ

jwt-auth

Use when implementing JWT authentication in FastAPI or Python projects. Triggers for: token generation, verification middleware, current user extraction, access token creation, token decoding, or role-based auth. NOT for: OAuth2 provider setup, OpenID Connect, or non-Python backends.

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o jwt-auth.zip https://jpskill.com/download/17385.zip && unzip -o jwt-auth.zip && rm jwt-auth.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17385.zip -OutFile "$d\jwt-auth.zip"; Expand-Archive "$d\jwt-auth.zip" -DestinationPath $d -Force; ri "$d\jwt-auth.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して jwt-auth.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → jwt-auth フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
2

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

JWT認証スキル

FastAPIおよびPythonアプリケーション向けのJWTトークン生成、検証、およびユーザー抽出のエキスパート実装です。

クイックリファレンス

操作 関数 場所
トークン生成 create_access_token(data, expires_delta=None) auth/jwt.py
トークン検証 verify_token(token: str) auth/dependencies.py
現在のユーザー取得 get_current_user(token: str) auth/dependencies.py
ペイロードからのユーザー取得 User.from_payload(payload) auth/dependencies.py

コアワークフロー

1. アクセストークンの生成

from auth.jwt import create_access_token

# サブジェクトを持つ基本的なトークン
token = create_access_token(data={"sub": "user@example.com"})

# カスタム有効期限(分)を持つトークン
from datetime import timedelta
token = create_access_token(
    data={"sub": "user@example.com", "roles": ["admin"]},
    expires_delta=timedelta(minutes=15)
)

# RBAC用のロールを持つトークン
token = create_access_token(data={"sub": "user@corp.com", "roles": ["editor", "viewer"]})

クレームの構造:

  • sub (必須): ユーザー識別子(メールアドレス、ID、またはユーザー名)
  • exp (自動): 有効期限
  • roles (オプション): 承認のためのロール文字列のリスト
  • カスタムクレーム: 必要に応じて追加のデータを追加

2. 依存関係によるエンドポイントの保護

from fastapi import APIRouter, Depends
from auth.dependencies import get_current_user

router = APIRouter()

@router.get("/protected")
def protected_route(user = Depends(get_current_user)):
    return {"message": f"Hello, {user.email}"}

3. ロールベースのアクセス制御

from auth.dependencies import get_current_user, RoleChecker

# ロールチェッカーの定義
admin_only = RoleChecker(allowed_roles=["admin"])

@router.delete("/admin-only")
def admin_endpoint(user = Depends(admin_only)):
    return {"message": "Admin access granted"}

4. JWTペイロードからのユーザー抽出

from auth.dependencies import get_current_user

# ユーザーモデルはJWTクレームから自動的に抽出されます
@router.get("/me")
def get_me(user = Depends(get_current_user)):
    return {
        "email": user.email,
        "roles": user.roles,
        "is_active": user.is_active
    }

セキュリティチェックリスト

  • [ ] 短い有効期限 + リフレッシュ: アクセストークンは15〜30分で期限切れになります。長期セッションのためにリフレッシュトークンフローを実装します
  • [ ] 機密データなし: パスワード、PII、またはシークレットをJWTクレームに入れないでください
  • [ ] 無効なもののブラックリスト: ログアウト用のトークンブラックリストを実装します(revoked_tokensセットを参照)
  • [ ] HS256アルゴリズム: HMAC-SHA256を使用します。algorithm="none"は絶対に使用しないでください
  • [ ] 有効期限の検証: 常にexpクレームを確認します。期限切れのトークンを拒否します

トークン構造

Header:
{
  "alg": "HS256",
  "typ": "JWT"
}

Payload:
{
  "sub": "user@example.com",
  "roles": ["user", "editor"],
  "exp": 1704067200,
  "iat": 1704063600
}

Signature: HMAC-SHA256(secret, header.payload)

ユーザーモデル

class User:
    email: str
    roles: List[str]
    is_active: bool = True

    @classmethod
    def from_payload(cls, payload: dict) -> "User":
        """Extract User from decoded JWT payload."""
        return cls(
            email=payload.get("sub", ""),
            roles=payload.get("roles", []),
            is_active=payload.get("is_active", True)
        )

@auth-integration Frontendとの統合

バックエンドのJWT実装は、フロントエンドの認証統合スキルと連携します。

  1. バックエンド: auth/jwt.py および auth/dependencies.py
  2. フロントエンド: React/Next.js認証コンテキストにauth-integrationスキルを使用します
  3. トークンフロー:
    • フロントエンドはログイン後にトークンをメモリ/ストレージに保存します
    • フロントエンドはAuthorization: Bearer <token>ヘッダーを含めます
    • バックエンドのHTTPBearer()依存関係は検証し、ユーザーを抽出します
    • 検証に失敗すると、401 Unauthorizedが返されます

ファイル出力

ファイル 目的
auth/jwt.py トークンの作成、エンコード、シークレット構成
auth/dependencies.py 検証とユーザー抽出のためのFastAPI依存関係

構成

次の環境変数を設定します。

  • JWT_SECRET_KEY: 長いランダムな文字列(少なくとも32文字)
  • JWT_ALGORITHM: "HS256"(デフォルト)
  • JWT_EXPIRATION_MINUTES: 15(推奨)

品質ゲート

完了とマークする前に:

  • [ ] トークンはHS256アルゴリズムを使用します
  • [ ] 有効期限は15〜30分に設定されています
  • [ ] クレームに機密データはありません
  • [ ] ログアウト用にブラックリストメカニズムが実装されています
  • [ ] auth-integrationフロントエンドスキルとの統合が文書化されています
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

JWT Authentication Skill

Expert implementation of JWT token generation, verification, and user extraction for FastAPI and Python applications.

Quick Reference

Operation Function Location
Generate token create_access_token(data, expires_delta=None) auth/jwt.py
Verify token verify_token(token: str) auth/dependencies.py
Get current user get_current_user(token: str) auth/dependencies.py
User from payload User.from_payload(payload) auth/dependencies.py

Core Workflows

1. Generate Access Token

from auth.jwt import create_access_token

# Basic token with subject
token = create_access_token(data={"sub": "user@example.com"})

# Token with custom expiry (minutes)
from datetime import timedelta
token = create_access_token(
    data={"sub": "user@example.com", "roles": ["admin"]},
    expires_delta=timedelta(minutes=15)
)

# Token with roles for RBAC
token = create_access_token(data={"sub": "user@corp.com", "roles": ["editor", "viewer"]})

Claims structure:

  • sub (required): User identifier (email, ID, or username)
  • exp (auto): Expiration time
  • roles (optional): List of role strings for authorization
  • Custom claims: Add any extra data as needed

2. Protect Endpoint with Dependency

from fastapi import APIRouter, Depends
from auth.dependencies import get_current_user

router = APIRouter()

@router.get("/protected")
def protected_route(user = Depends(get_current_user)):
    return {"message": f"Hello, {user.email}"}

3. Role-Based Access Control

from auth.dependencies import get_current_user, RoleChecker

# Define role checker
admin_only = RoleChecker(allowed_roles=["admin"])

@router.delete("/admin-only")
def admin_endpoint(user = Depends(admin_only)):
    return {"message": "Admin access granted"}

4. Extract User from JWT Payload

from auth.dependencies import get_current_user

# User model automatically extracted from JWT claims
@router.get("/me")
def get_me(user = Depends(get_current_user)):
    return {
        "email": user.email,
        "roles": user.roles,
        "is_active": user.is_active
    }

Security Checklist

  • [ ] Short expiry + refresh: Access tokens expire in 15-30 minutes; implement refresh token flow for long sessions
  • [ ] No sensitive data: Never put passwords, PII, or secrets in JWT claims
  • [ ] Blacklist invalid: Implement token blacklist for logout (see revoked_tokens set)
  • [ ] HS256 algorithm: Use HMAC-SHA256; never use algorithm="none"
  • [ ] Verify expiration: Always check exp claim; reject expired tokens

Token Structure

Header:
{
  "alg": "HS256",
  "typ": "JWT"
}

Payload:
{
  "sub": "user@example.com",
  "roles": ["user", "editor"],
  "exp": 1704067200,
  "iat": 1704063600
}

Signature: HMAC-SHA256(secret, header.payload)

User Model

class User:
    email: str
    roles: List[str]
    is_active: bool = True

    @classmethod
    def from_payload(cls, payload: dict) -> "User":
        """Extract User from decoded JWT payload."""
        return cls(
            email=payload.get("sub", ""),
            roles=payload.get("roles", []),
            is_active=payload.get("is_active", True)
        )

Integration with @auth-integration Frontend

The backend JWT implementation pairs with the frontend auth integration skill:

  1. Backend: auth/jwt.py and auth/dependencies.py
  2. Frontend: Use auth-integration skill for React/Next.js auth context
  3. Token flow:
    • Frontend stores token in memory/storage after login
    • Frontend includes Authorization: Bearer <token> header
    • Backend HTTPBearer() dependency validates and extracts user
    • Failed verification returns 401 Unauthorized

File Outputs

File Purpose
auth/jwt.py Token creation, encoding, secret config
auth/dependencies.py FastAPI dependencies for verification and user extraction

Configuration

Set these environment variables:

  • JWT_SECRET_KEY: Long random string (at least 32 chars)
  • JWT_ALGORITHM: "HS256" (default)
  • JWT_EXPIRATION_MINUTES: 15 (recommended)

Quality Gates

Before marking complete:

  • [ ] Tokens use HS256 algorithm
  • [ ] Expiration set to 15-30 minutes
  • [ ] No sensitive data in claims
  • [ ] Blacklist mechanism implemented for logout
  • [ ] Integration with auth-integration frontend skill documented

同梱ファイル

※ ZIPに含まれるファイル一覧。`SKILL.md` 本体に加え、参考資料・サンプル・スクリプトが入っている場合があります。