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.
Best use case
jwt-auth is best used when you need a repeatable AI agent workflow instead of a one-off prompt. It is especially useful for teams working in multi. 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.
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.
Users should expect a more consistent workflow output, faster repeated execution, and less time spent rewriting prompts from scratch.
Practical example
Example input
Use the "jwt-auth" skill to help with this workflow task. Context: 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.
Example output
A structured workflow result with clearer steps, more consistent formatting, and an output that is easier to reuse in the next run.
When to use this skill
- Use this skill when you want a reusable workflow rather than writing the same prompt again and again.
When not to use this skill
- Do not use this when you only need a one-off answer and do not need a reusable workflow.
- Do not use it if you cannot install or maintain the related files, repository context, or supporting tools.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/jwt-auth/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How jwt-auth Compares
| Feature / Agent | jwt-auth | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
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.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# 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
```python
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
```python
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
```python
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
```python
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
```python
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 documentedRelated Skills
authentication-setup
Design and implement authentication and authorization systems. Use when setting up user login, JWT tokens, OAuth, session management, or role-based access control. Handles password security, token management, SSO integration.
seo-authority-builder
Analyzes content for E-E-A-T signals and suggests improvements to build authority and trust. Identifies missing credibility elements. Use PROACTIVELY for YMYL topics.
nextjs-supabase-auth
Expert integration of Supabase Auth with Next.js App Router Use when: supabase auth next, authentication next.js, login supabase, auth middleware, protected route.
microsoft-azure-webjobs-extensions-authentication-events-dotnet
Microsoft Entra Authentication Events SDK for .NET. Azure Functions triggers for custom authentication extensions. Use for token enrichment, custom claims, attribute collection, and OTP customization in Entra ID. Triggers: "Authentication Events", "WebJobsAuthenticationEventsTrigger", "OnTokenIssuanceStart", "OnAttributeCollectionStart", "custom claims", "token enrichment", "Entra custom extension", "authentication extension".
clerk-auth
Expert patterns for Clerk auth implementation, middleware, organizations, webhooks, and user sync Use when: adding authentication, clerk auth, user authentication, sign in, sign up.
broken-authentication
This skill should be used when the user asks to "test for broken authentication vulnerabilities", "assess session management security", "perform credential stuffing tests", "evaluate ...
broken-authentication-testing
This skill should be used when the user asks to "test for broken authentication vulnerabilities", "assess session management security", "perform credential stuffing tests", "evaluate password policies", "test for session fixation", or "identify authentication bypass flaws". It provides comprehensive techniques for identifying authentication and session management weaknesses in web applications.
auth-implementation-patterns
Master authentication and authorization patterns including JWT, OAuth2, session management, and RBAC to build secure, scalable access control systems. Use when implementing auth systems, securing APIs, or debugging security issues.
convex-setup-auth
Sets up Convex authentication with user management, identity mapping, and access control. Use this skill when adding login or signup to a Convex app, configuring Convex Auth, Clerk, WorkOS AuthKit, Auth0, or custom JWT providers, wiring auth.config.ts, protecting queries and mutations with ctx.auth.getUserIdentity(), creating a users table with identity mapping, or setting up role-based access control, even if the user just says "add auth" or "make it require login."
firebase-auth-basics
Guide for setting up and using Firebase Authentication. Use this skill when the user's app requires user sign-in, user management, or secure data access using auth rules.
auth-analyzer
Review and analyze authentication and authorization patterns for security vulnerabilities.
web-auth
Authentication patterns for React web applications. Use when implementing login flows, OAuth, JWT handling, session management, or protected routes in React web apps.