用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/tools-only/X-Skills --skill build-auth-system命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
正在显示 SKILL.md
基于 SOC 职业分类
| name | build-auth-system |
| description | Build comprehensive API authentication and authorization system |
| shortcut | auth |
| category | api |
| difficulty | intermediate |
| estimated_time | 5-10 minutes |
| version | 2.0.0 |
Implements a complete authentication and authorization system for your API, supporting JWT tokens, OAuth2 flows, API keys, session-based auth, and multi-factor authentication. Generates production-ready auth middleware, user management, and role-based access control.
Use this command when:
Do NOT use this command for:
Before running this command, ensure:
Examines your application to determine the best auth strategy:
Creates the core authentication system:
Sets up access control mechanisms:
Implements additional security measures:
auth-system/
├── models/
│ ├── user.js # User model with auth fields
│ ├── role.js # Role definitions
│ └── permission.js # Permission mappings
├── middleware/
│ ├── authenticate.js # Auth verification middleware
│ ├── authorize.js # Permission checking
│ └── rate-limit.js # Rate limiting
├── services/
│ ├── auth.service.js # Core auth logic
│ ├── token.service.js # Token management
│ └── password.service.js # Password utilities
├── routes/
│ ├── auth.routes.js # Auth endpoints
│ └── user.routes.js # User management
├── config/
│ ├── auth.config.js # Auth configuration
│ └── jwt.config.js # JWT settings
└── tests/
└── auth.test.js # Auth system tests
User Input:
/auth --type jwt --framework express
Generated Authentication Service:
// services/auth.service.js
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
class AuthService {
constructor() {
this.saltRounds = 12;
this.tokenExpiry = '1h';
this.refreshTokenExpiry = '7d';
}
async register(userData) {
// Validate input
this.validateRegistration(userData);
// Check if user exists
const existing = await User.findOne({ email: userData.email });
if (existing) {
throw new ConflictError('User already exists');
}
// Hash password
const hashedPassword = await bcrypt.hash(userData.password, this.saltRounds);
// Create user
const user = .({
...userData,
: hashedPassword,
: crypto.().(),
: ,
: ()
});
.(user., user.);
{ accessToken, refreshToken } = .(user);
{
: .(user),
accessToken,
refreshToken
};
}
() {
user = .({ email }).();
(!user) {
();
}
isValid = bcrypt.(password, user.);
(!isValid) {
.(user);
();
}
(user. && user. > .()) {
();
}
(!user. && process.. === ) {
();
}
.(user);
{ accessToken, refreshToken } = .(user);
user. = ();
user.();
{
: .(user),
accessToken,
refreshToken
};
}
() {
payload = {
: user.,
: user.,
: user.
};
accessToken = jwt.(
payload,
process..,
{ : . }
);
refreshToken = jwt.(
{ : user., : },
process..,
{ : . }
);
.({
: user.,
: refreshToken,
: (.() + * * * * )
});
{ accessToken, refreshToken };
}
() {
decoded = jwt.(refreshToken, process..);
storedToken = .({
: refreshToken,
: decoded.,
: { : () }
});
(!storedToken) {
();
}
user = .(decoded.);
(!user) {
();
}
accessToken = jwt.(
{
: user.,
: user.,
: user.
},
process..,
{ : . }
);
{ accessToken };
}
() {
.({ userId, : refreshToken });
.({
: refreshToken,
: (.() + * * * * )
});
{ : };
}
}
Generated Middleware:
// middleware/authenticate.js
const jwt = require('jsonwebtoken');
const authenticate = async (req, res, next) => {
try {
// Extract token
const token = extractToken(req);
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
// Check blacklist
const isBlacklisted = await BlacklistedToken.exists({ token });
if (isBlacklisted) {
return res.status(401).json({ error: 'Token revoked' });
}
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Get user
const user = await User.findById(decoded.id).select('-password');
if (!user) {
return res.status(401).json({ error: });
}
req. = user;
req. = user.;
();
} (error) {
(error. === ) {
res.().({ : });
}
(error. === ) {
res.().({ : });
}
res.().({ : });
}
};
= () => {
{
(!req.) {
res.().({ : });
}
hasRole = req...( allowedRoles.(role));
(!hasRole) {
res.().({ : });
}
();
};
};
User Input:
/auth --type oauth2-provider --framework fastapi
Generated OAuth2 Provider:
# services/oauth2_provider.py
from datetime import datetime, timedelta
from typing import Optional
import secrets
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from sqlalchemy.orm import Session
class OAuth2Provider:
def __init__(self):
self.pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
self.oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
self.SECRET_KEY = os.getenv("SECRET_KEY")
self.ALGORITHM = "HS256"
self.ACCESS_TOKEN_EXPIRE_MINUTES = 30
self.REFRESH_TOKEN_EXPIRE_DAYS = 7
async def create_client(self, client_data: dict, db: Session):
"""Register OAuth2 client application"""
client = OAuth2Client(
client_id=secrets.token_urlsafe(32),
client_secret=self.hash_secret(secrets.token_urlsafe(64)),
name=client_data[],
redirect_uris=client_data[],
grant_types=client_data[],
response_types=client_data[],
scope=client_data[],
created_at=datetime.utcnow()
)
db.add(client)
db.commit()
client
():
client = db.query(OAuth2Client).(
OAuth2Client.client_id == client_id
).first()
client redirect_uri client.redirect_uris:
HTTPException(
status_code=,
detail=
)
auth_code = AuthorizationCode(
code=secrets.token_urlsafe(),
client_id=client_id,
user_id=user.,
redirect_uri=redirect_uri,
scope=scope,
expires_at=datetime.utcnow() + timedelta(minutes=)
)
db.add(auth_code)
db.commit()
auth_code.code
():
client = .verify_client(client_id, client_secret, db)
auth_code = db.query(AuthorizationCode).(
AuthorizationCode.code == code,
AuthorizationCode.client_id == client_id,
AuthorizationCode.redirect_uri == redirect_uri,
AuthorizationCode.expires_at > datetime.utcnow()
).first()
auth_code:
HTTPException(
status_code=,
detail=
)
access_token = .create_access_token(
data={: (auth_code.user_id), : auth_code.scope}
)
refresh_token = .create_refresh_token(
data={: (auth_code.user_id)}
)
db.delete(auth_code)
db.commit()
{
: access_token,
: refresh_token,
: ,
: .ACCESS_TOKEN_EXPIRE_MINUTES *
}
User Input:
/auth --type api-key --with-rate-limiting
Generated API Key System:
// services/apikey.service.js
const crypto = require('crypto');
const { RateLimiter } = require('./rate-limiter');
class APIKeyService {
constructor() {
this.rateLimiter = new RateLimiter();
}
async generateAPIKey(userId, name, permissions = []) {
// Generate secure API key
const apiKey = `sk_${process.env.NODE_ENV}_${crypto.randomBytes(32).toString('hex')}`;
const hashedKey = crypto
.createHash('sha256')
.update(apiKey)
.digest('hex');
// Store key metadata
const keyRecord = await APIKey.create({
userId,
name,
keyHash: hashedKey,
prefix: apiKey.substring(0, 7),
permissions,
lastUsed: null,
expiresAt: null, // Optional expiration
createdAt: new ()
});
{
: keyRecord.,
apiKey,
name,
permissions,
: keyRecord.
};
}
() {
hashedKey = crypto
.()
.(apiKey)
.();
keyRecord = .({
: hashedKey,
: [
{ : },
{ : { : () } }
]
});
(!keyRecord) {
();
}
rateLimitOk = ..(
keyRecord.,
keyRecord. ||
);
(!rateLimitOk) {
();
}
keyRecord. = ();
keyRecord. += ;
keyRecord.();
user = .(keyRecord.);
{
user,
: keyRecord.,
: keyRecord.
};
}
}
Symptoms: Registration fails with password validation error Cause: Password doesn't meet complexity requirements Solution:
// Implement password strength validation
const passwordStrength = {
minLength: 8,
requireUppercase: true,
requireLowercase: true,
requireNumbers: true,
requireSymbols: true
};
Symptoms: 401 Unauthorized after token lifetime Cause: Access token has expired Solution:
// Use refresh token to get new access token
const { accessToken } = await authService.refreshAccessToken(refreshToken);
Symptoms: 403 Forbidden after multiple failed attempts Cause: Brute force protection triggered Solution:
// Implement exponential backoff
const lockoutDuration = Math.pow(2, failedAttempts) * 60 * 1000;
--typejwt, oauth2, api-key, session, basicjwt/auth --type oauth2--with-mfa/auth --with-mfa--with-social/auth --with-social google,github,facebook✅ DO:
❌ DON'T:
💡 TIPS:
/api-rate-limiter - Add rate limiting to APIs/api-security-scanner - Scan for vulnerabilities/user-management - User CRUD operations/session-manager - Session handling utilities⚠️ Security Considerations:
Solution: Set JWT_SECRET environment variable with strong random value
Solution: Configure session store (Redis recommended for production)
Solution: Verify redirect URI is whitelisted in OAuth2 provider
Last updated: 2025-10-11 Quality score: 9+/10 Tested with: Express, FastAPI, Django, Spring Boot