API Security Best Practices
БесплатноБез исполняемых скриптовНе проверенImplement secure API design patterns including authentication, authorization, input validation, rate limiting, and protection against common API…
от modbender★ 21 звезда на GitHubОб этом скилле
API Security Best Practices
Implement secure API design patterns including authentication, authorization, input validation, rate limiting, and protection against common API vulnerabilities.
Description
USE WHEN:
- Designing new API endpoints
- Securing existing APIs
- Implementing authentication and authorization (JWT, OAuth 2.0, API keys)
- Setting up rate limiting and throttling
- Protecting against injection attacks (SQL, XSS, command)
- Conducting API security reviews or preparing for audits
- Handling sensitive data in APIs
- Building REST, GraphQL, or WebSocket APIs
DON'T USE WHEN:
- Need vulnerability scanning (use
vulnerability-scannerskill) - Building frontend-only apps with no API
- Need network-level security (firewalls, WAF config)
OUTPUTS:
- Secure authentication implementations (JWT, refresh tokens)
- Input validation schemas (Zod, Joi)
- Rate limiting configurations
- Security middleware examples
- OWASP API Top 10 compliance guidance
How It Works
Step 1: Authentication & Authorization
- Choose authentication method (JWT, OAuth 2.0, API keys)
- Implement token-based authentication
- Set up role-based access control (RBAC)
- Secure session management
- Implement multi-factor authentication (MFA)
Step 2: Input Validation & Sanitization
- Validate all input data
- Sanitize user inputs
- Use parameterized queries
- Implement request schema validation
- Prevent SQL injection, XSS, and command injection
Step 3: Rate Limiting & Throttling
- Implement rate limiting per user/IP
- Set up API throttling
- Configure request quotas
- Handle rate limit errors gracefully
- Monitor for suspicious activity
Step 4: Data Protection
- Encrypt data in transit (HTTPS/TLS)
- Encrypt sensitive data at rest
- Implement proper error handling (no data leaks)
- Sanitize error messages
- Use secure headers
JWT Authentication Implementation
Generate Secure JWT Tokens
// auth.js
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
app.post('/api/auth/login', async (req, res) => {
try {
const { email, password } = req.body;
// Validate input
if (!email || !password) {
return res.status(400).json({ error: 'Email and password required' });
}
// Find user
const user = await db.user.findUnique({ where: { email } });
if (!user) {
// Don't reveal if user exists
return res.status(401).json({ error: 'Invalid credentials' });
}
// Verify password
const validPassword = await bcrypt.compare(password, user.passwordHash);
if (!validPassword) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Generate JWT token
const token = jwt.sign(
{ userId: user.id, email: user.email, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '1h', issuer: 'your-app', audience: 'your-app-users' }
);
// Generate refresh token
const refreshToken = jwt.sign(
{ userId: user.id },
process.env.JWT_REFRESH_SECRET,
{ expiresIn: '7d' }
);
// Store refresh token in database
await db.refreshToken.create({
data: {
token: refreshToken,
userId: user.id,
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
}
});
res.json({ token, refreshToken, expiresIn: 3600 });
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ error: 'An error occurred during login' });
}
});
JWT Verification Middleware
// middleware/auth.js
const jwt = require('jsonwebtoken');
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
if (!token) {
return res.status(401).json({ error: 'Access token required' });
}
jwt.verify(
token,
process.env.JWT_SECRET,
{ issuer: 'your-app', audience: 'your-app-users' },
(err, user) => {
if (err) {
if (err.name === 'TokenExpiredError') {
return res.status(401).json({ error: 'Token expired' });
}
return res.status(403).json({ error: 'Invalid token' });
}
req.user = user;
next();
}
);
}
module.exports = { authenticateToken };
Input Validation (SQL Injection Prevention)
❌ Vulnerable Code
// NEVER DO THIS - SQL Injection vulnerability
app.get('/api/users/:id', async (req, res) => {
const userId = req.params.id;
const query = `SELECT * FROM users WHERE id = '${userId}'`;
const user = await db.query(query);
res.json(user);
});
// Attack: GET /api/users/1' OR '1'='1 → Returns all users!
✅ Safe: Parameterized Queries
ap
Установить API Security Best Practices в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл API Security Best Practices?
Implement secure API design patterns including authentication, authorization, input validation, rate limiting, and protection against common API vulnerabilities.
Как установить скилл API Security Best Practices?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл API Security Best Practices запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic