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.
What this skill does
# 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": "[email protected]"})
# Token with custom expiry (minutes)
from datetime import timedelta
token = create_access_token(
data={"sub": "[email protected]", "roles": ["admin"]},
expires_delta=timedelta(minutes=15)
)
# Token with roles for RBAC
token = create_access_token(data={"sub": "[email protected]", "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": "[email protected]",
"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 documented
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.