api-security
Comprehensive API security guidance covering authentication methods, rate limiting, input validation, CORS, security headers, and protection against OWASP API Top 10 vulnerabilities. Use when designing API authentication, implementing rate limiting, configuring CORS, setting security headers, or reviewing API security.
What this skill does
# API Security
Comprehensive guidance for securing APIs, covering authentication, authorization, rate limiting, validation, and protection against common API attacks.
## When to Use This Skill
Use this skill when:
- Choosing API authentication methods
- Implementing rate limiting
- Configuring CORS policies
- Setting security headers
- Validating API inputs
- Preventing data exposure
- Protecting against BOLA/IDOR attacks
- Implementing request signing
- Securing API gateways
## OWASP API Security Top 10 (2023)
| Rank | Vulnerability | Description | Mitigation |
|------|--------------|-------------|------------|
| API1 | Broken Object Level Authorization | Access to unauthorized objects | Object-level authorization checks |
| API2 | Broken Authentication | Authentication flaws | Strong authentication, MFA |
| API3 | Broken Object Property Level Authorization | Excessive data exposure, mass assignment | Response filtering, allowlists |
| API4 | Unrestricted Resource Consumption | DoS via resource exhaustion | Rate limiting, pagination |
| API5 | Broken Function Level Authorization | Access to unauthorized functions | Function-level authz checks |
| API6 | Unrestricted Access to Sensitive Business Flows | Abuse of business logic | Rate limiting, fraud detection |
| API7 | Server Side Request Forgery (SSRF) | Server makes malicious requests | URL validation, allowlists |
| API8 | Security Misconfiguration | Improper configuration | Security hardening, automation |
| API9 | Improper Inventory Management | Unknown/unmanaged APIs | API inventory, versioning |
| API10 | Unsafe Consumption of APIs | Trusting third-party APIs | Validate external responses |
## API Authentication Methods
### Method Comparison
| Method | Use Case | Pros | Cons |
|--------|----------|------|------|
| API Keys | Simple services, internal APIs | Easy to implement | No user context, hard to rotate |
| OAuth 2.0 Bearer Tokens | User-delegated access | Standard, scoped | Token management complexity |
| JWT | Stateless authentication | Self-contained, scalable | Size, revocation challenges |
| mTLS | Service-to-service | Strong identity, encryption | Certificate management |
| HMAC Signatures | Request integrity | Tamper-proof | Implementation complexity |
### API Key Security
```csharp
using System.Security.Cryptography;
using Microsoft.AspNetCore.Http;
/// <summary>
/// API key authentication handler using ASP.NET Core middleware.
/// Uses CryptographicOperations.FixedTimeEquals for timing-safe comparison.
/// </summary>
public sealed class ApiKeyAuthenticationHandler(
IApiKeyValidator validator,
ILogger<ApiKeyAuthenticationHandler> logger)
{
private const string ApiKeyHeader = "X-API-Key";
private const string ClientIdHeader = "X-Client-ID";
public async Task<bool> ValidateAsync(HttpContext context, CancellationToken ct = default)
{
if (!context.Request.Headers.TryGetValue(ApiKeyHeader, out var apiKeyHeader))
{
logger.LogWarning("API key required but not provided");
return false;
}
var apiKey = apiKeyHeader.ToString();
var clientId = context.Request.Headers[ClientIdHeader].ToString();
// Hash the provided key
var providedHash = SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(apiKey));
// Retrieve stored hash for this client
var storedHash = await validator.GetKeyHashAsync(clientId, ct);
if (storedHash is null)
{
logger.LogWarning("No stored key found for client {ClientId}", clientId);
return false;
}
// Timing-safe comparison to prevent timing attacks
if (!CryptographicOperations.FixedTimeEquals(providedHash, storedHash))
{
logger.LogWarning("Invalid API key for client {ClientId}", clientId);
return false;
}
return true;
}
}
public interface IApiKeyValidator
{
Task<byte[]?> GetKeyHashAsync(string clientId, CancellationToken ct = default);
}
// Best practices for API keys:
// 1. Use sufficiently long, random keys (32+ bytes)
// 2. Transmit only over HTTPS
// 3. Store hashed, not plaintext
// 4. Implement key rotation
// 5. Scope keys to specific operations
// 6. Rate limit per key
```
### Request Signing (HMAC)
```csharp
using System.Security.Cryptography;
using System.Text;
/// <summary>
/// HMAC-SHA256 request signer for API authentication.
/// Generates and verifies request signatures for tamper-proof requests.
/// </summary>
public sealed class RequestSigner
{
private readonly string _apiKey;
private readonly byte[] _secretKey;
public RequestSigner(string apiKey, string secretKey)
{
_apiKey = apiKey;
_secretKey = Encoding.UTF8.GetBytes(secretKey);
}
/// <summary>
/// Generate signature headers for a request.
/// </summary>
public Dictionary<string, string> SignRequest(string method, string path, string body = "")
{
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
var stringToSign = $"{method}\n{path}\n{timestamp}\n{body}";
using var hmac = new HMACSHA256(_secretKey);
var signature = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
return new Dictionary<string, string>
{
["X-API-Key"] = _apiKey,
["X-Timestamp"] = timestamp,
["X-Signature"] = Convert.ToBase64String(signature)
};
}
}
/// <summary>
/// Verifies HMAC-SHA256 request signatures.
/// </summary>
public sealed class SignatureVerifier(ISecretKeyProvider secretProvider)
{
private static readonly TimeSpan MaxClockSkew = TimeSpan.FromMinutes(5);
/// <summary>
/// Verify request signature with timing-safe comparison.
/// </summary>
public async Task<bool> VerifyAsync(
string apiKey,
string timestamp,
string signature,
string method,
string path,
string body = "",
CancellationToken ct = default)
{
// Check timestamp freshness (5-minute window)
if (!long.TryParse(timestamp, out var requestTime))
return false;
var requestDateTime = DateTimeOffset.FromUnixTimeSeconds(requestTime);
if (Math.Abs((DateTimeOffset.UtcNow - requestDateTime).TotalSeconds) > MaxClockSkew.TotalSeconds)
return false;
// Retrieve secret key for this API key
var secretKey = await secretProvider.GetSecretAsync(apiKey, ct);
if (secretKey is null)
return false;
// Regenerate expected signature
var stringToSign = $"{method}\n{path}\n{timestamp}\n{body}";
using var hmac = new HMACSHA256(secretKey);
var expected = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
// Timing-safe comparison to prevent timing attacks
var provided = Convert.FromBase64String(signature);
return CryptographicOperations.FixedTimeEquals(expected, provided);
}
}
public interface ISecretKeyProvider
{
Task<byte[]?> GetSecretAsync(string apiKey, CancellationToken ct = default);
}
```
## Rate Limiting
### Rate Limiting Strategies
| Strategy | Description | Use Case |
|----------|-------------|----------|
| Fixed Window | Count requests in fixed time windows | Simple, predictable |
| Sliding Window | Rolling window of requests | Smoother limits |
| Token Bucket | Tokens replenish over time | Allow bursts |
| Leaky Bucket | Requests processed at fixed rate | Smooth traffic |
### Implementation (Token Bucket with ASP.NET Core)
```csharp
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.RateLimiting;
using StackExchange.Redis;
using System.Threading.RateLimiting;
/// <summary>
/// Token bucket rate limiting result.
/// </summary>
public sealed record RateLimitResult(
bool IsAllowed,
int Remaining,
long ResetTimeUnix,
int RetryAfterSeconds = 0);
/// <summary>
/// Token bucket ratRelated 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.