Get the FREE Ultimate OpenClaw Setup Guide →

api-authentication

Scanned
npx machina-cli add skill secondsky/claude-skills/api-authentication --openclaw
Files (1)
SKILL.md
2.6 KB

API Authentication

Implement secure authentication mechanisms for APIs using modern standards and best practices.

Authentication Methods

MethodUse CaseSecurity Level
JWTStateless auth, SPAsHigh
OAuth 2.0Third-party integrationHigh
API KeysService-to-serviceMedium
SessionTraditional web appsHigh

JWT Implementation (Node.js)

const jwt = require('jsonwebtoken');

const generateTokens = (user) => ({
  accessToken: jwt.sign(
    { userId: user.id, role: user.role },
    process.env.JWT_SECRET,
    { expiresIn: '15m' }
  ),
  refreshToken: jwt.sign(
    { userId: user.id, type: 'refresh' },
    process.env.REFRESH_SECRET,
    { expiresIn: '7d' }
  )
});

const authMiddleware = (req, res, next) => {
  const authHeader = req.headers.authorization;

  // Validate authorization header format
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Malformed authorization header' });
  }

  const parts = authHeader.split(' ');
  if (parts.length !== 2) {
    return res.status(401).json({ error: 'Malformed authorization header' });
  }

  const token = parts[1];
  if (!token) {
    return res.status(401).json({ error: 'No token provided' });
  }

  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch (err) {
    res.status(401).json({ error: 'Invalid token' });
  }
};

Security Requirements

  • Always use HTTPS
  • Store tokens in HttpOnly cookies (not localStorage)
  • Hash passwords with bcrypt (cost factor 12+)
  • Implement rate limiting on auth endpoints
  • Rotate secrets regularly
  • Never transmit tokens in URLs

Security Headers

app.use((req, res, next) => {
  res.setHeader('X-Content-Type-Options', 'nosniff');
  res.setHeader('X-Frame-Options', 'DENY');
  res.setHeader('Strict-Transport-Security', 'max-age=31536000');
  next();
});

Additional Implementations

See references/python-flask.md for:

  • Flask JWT with role-based access control decorators
  • OAuth 2.0 Google integration with Authlib
  • API key authentication with secure hashing

Common Mistakes to Avoid

  • Storing plain-text passwords
  • Using weak JWT secrets
  • Ignoring token expiration
  • Disabling HTTPS in production
  • Logging sensitive tokens

Source

git clone https://github.com/secondsky/claude-skills/blob/main/plugins/api-authentication/skills/api-authentication/SKILL.mdView on GitHub

Overview

API Authentication ensures only authorized clients access your services using modern standards. It covers JWT for stateless tokens, OAuth 2.0 for third-party integrations, and API keys for service-to-service calls, complemented by best practices like HTTPS, HttpOnly cookies, and token rotation to minimize risk.

How This Skill Works

Tokens are issued after successful authentication. Access tokens are short-lived, while refresh tokens allow obtaining new access tokens. Incoming requests are protected by a Bearer token middleware and reinforced with security headers, HTTPS, and routine secret rotation to maintain integrity.

When to Use It

  • When building a SPA that requires stateless authentication with short-lived access tokens (JWT).
  • For integrating with third-party services using OAuth 2.0.
  • When service-to-service communication requires lightweight API key authentication.
  • When migrating traditional session-based apps to token-based auth.
  • When you need lifecycle controls like token expiration, rotation, and revocation.

Quick Start

  1. Step 1: Choose your auth method (JWT, OAuth 2.0, or API Key) and define token lifetimes.
  2. Step 2: Implement token generation and a Bearer auth middleware (e.g., generateTokens and authMiddleware).
  3. Step 3: Apply security headers, HTTPS, HttpOnly cookies, rate limiting, and plan for secret rotation.

Best Practices

  • Use HTTPS everywhere to protect in transit.
  • Store tokens in HttpOnly cookies, not in localStorage or sessionStorage.
  • Hash and securely manage secrets; rotate them regularly.
  • Implement rate limiting on authentication endpoints to deter abuse.
  • Never transmit tokens in URLs or as query parameters.

Example Use Cases

  • JWT-based stateless authentication for a React/Next.js single-page app.
  • OAuth 2.0 flow for integrating a partner service with your API.
  • API key authentication for internal microservices communication.
  • Session-less API access for mobile apps using short-lived access tokens.
  • Enforced security headers and Strict-Transport-Security in API responses.

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers