home / skills / secondsky / claude-skills / api-authentication

This skill helps you implement secure API authentication using JWT, OAuth 2.0, and API keys with best practices and token management.

npx playbooks add skill secondsky/claude-skills --skill api-authentication

Review the files below or copy the command above to add this skill to your agents.

Files (2)
SKILL.md
2.6 KB
---
name: api-authentication
description: Secure API authentication with JWT, OAuth 2.0, API keys. Use for authentication systems, third-party integrations, service-to-service communication, or encountering token management, security headers, auth flow errors.
---

# API Authentication

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

## Authentication Methods

| Method | Use Case | Security Level |
|--------|----------|----------------|
| JWT | Stateless auth, SPAs | High |
| OAuth 2.0 | Third-party integration | High |
| API Keys | Service-to-service | Medium |
| Session | Traditional web apps | High |

## JWT Implementation (Node.js)

```javascript
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

```javascript
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](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

Overview

This skill implements secure API authentication patterns using JWT, OAuth 2.0, and API keys. It packages production-ready advice, middleware patterns, and security hardening tips for building authentication systems in TypeScript and Node.js environments. Use it to standardize token handling, session flows, and service-to-service auth in modern web and cloud apps.

How this skill works

The skill provides generation and verification patterns for access and refresh tokens (JWT), middleware to validate Authorization headers, and patterns for API key and OAuth flows. It includes security header middleware, recommendations for token storage and rotation, and practical checks to prevent common mistakes like malformed headers or invalid tokens. Example snippets and rules show how to integrate with HTTPS, HttpOnly cookies, and rate limiting.

When to use it

  • Building stateless authentication for single-page applications or APIs
  • Integrating third-party OAuth 2.0 providers for user sign-in
  • Securing service-to-service communication with API keys or client credentials
  • Handling token issuance, refresh flows, and role claims
  • Hardening auth endpoints against token leakage, replay, and brute force

Best practices

  • Always serve auth endpoints over HTTPS and enforce HSTS
  • Store tokens in HttpOnly, Secure cookies; avoid localStorage for sensitive tokens
  • Use strong, rotated secrets and keep access token lifetimes short with refresh tokens
  • Hash passwords with bcrypt (cost factor 12+) and never store plaintext credentials
  • Add rate limiting and monitoring on authentication endpoints to detect abuse
  • Set security headers (X-Frame-Options, X-Content-Type-Options, Strict-Transport-Security)

Example use cases

  • JWT access + refresh token flow for a React SPA with a TypeScript Node API
  • OAuth 2.0 Google sign-in for consumer authentication and delegated access
  • API key authentication for internal microservice calls with hashed keys
  • Service-to-service client credentials flow for backend integrations
  • Role-based access control using JWT claims verified in middleware

FAQ

Should I store access tokens in localStorage?

No. Store tokens in HttpOnly, Secure cookies to reduce XSS risk; if using localStorage, accept higher exposure and add additional mitigations.

How long should access and refresh tokens live?

Use short access token expiries (e.g., 10–15 minutes) and longer refresh tokens (days to weeks) with rotation and revocation support.