home / skills / secondsky / claude-skills / session-management

This skill helps you implement secure session management using JWTs, Redis storage, and proper cookie configurations to safeguard user sessions.

npx playbooks add skill secondsky/claude-skills --skill session-management

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

Files (1)
SKILL.md
2.5 KB
---
name: session-management
description: Implements secure session management with JWT tokens, Redis storage, refresh flows, and proper cookie configuration. Use when building authentication systems, managing user sessions, or implementing secure logout functionality.
---

# Session Management

Implement secure session management with proper token handling and storage.

## Token-Based Sessions

```javascript
const jwt = require('jsonwebtoken');

function generateTokens(user) {
  const accessToken = jwt.sign(
    { userId: user.id, role: user.role, type: 'access' },
    process.env.JWT_SECRET,
    { expiresIn: '1h' }
  );

  const refreshToken = jwt.sign(
    { userId: user.id, type: 'refresh' },
    process.env.REFRESH_SECRET,
    { expiresIn: '7d' }
  );

  return { accessToken, refreshToken };
}
```

## Redis Session Storage

```javascript
const redis = require('redis');
const client = redis.createClient();

class SessionStore {
  async create(userId, sessionData) {
    const sessionId = crypto.randomUUID();
    await client.hSet(`sessions:${userId}`, sessionId, JSON.stringify({
      ...sessionData,
      createdAt: Date.now()
    }));
    await client.expire(`sessions:${userId}`, 86400 * 7);
    return sessionId;
  }

  async invalidateAll(userId) {
    await client.del(`sessions:${userId}`);
  }
}
```

## Cookie Configuration

```javascript
app.use(session({
  name: 'session',
  secret: process.env.SESSION_SECRET,
  cookie: {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'strict',
    maxAge: 3600000, // 1 hour
    domain: '.example.com'
  },
  resave: false,
  saveUninitialized: false
}));
```

## Token Refresh Flow

```javascript
app.post('/auth/refresh', async (req, res) => {
  const { refreshToken } = req.cookies;

  try {
    const payload = jwt.verify(refreshToken, process.env.REFRESH_SECRET);
    if (payload.type !== 'refresh') throw new Error('Invalid token type');

    const user = await User.findById(payload.userId);
    const tokens = generateTokens(user);

    res.cookie('accessToken', tokens.accessToken, cookieOptions);
    res.json({ success: true });
  } catch (err) {
    res.status(401).json({ error: 'Invalid refresh token' });
  }
});
```

## Security Requirements

- Use HTTPS exclusively
- Set httpOnly and sameSite on cookies
- Implement proper token expiration
- Use strong, unique secrets per environment
- Validate signatures on every request

## Never Do

- Store sensitive data in tokens
- Transmit tokens via URL parameters
- Use weak or shared secrets
- Skip signature validation

Overview

This skill implements secure session management for web applications using JWT tokens, Redis-backed session storage, refresh flows, and hardened cookie configuration. It provides a production-ready pattern for issuing access and refresh tokens, storing session metadata in Redis, and rotating tokens via a refresh endpoint. The implementation emphasizes secure defaults: HTTPS-only cookies, httpOnly and sameSite flags, token expiration, and signature validation. Use it to add robust session lifecycle controls, logout, and multi-session management to your auth stack.

How this skill works

The skill generates short-lived access tokens and longer-lived refresh tokens with distinct secrets and token types to prevent misuse. Session metadata and per-user session entries are stored in Redis so you can enumerate or invalidate sessions (single or all). Cookies are set with httpOnly, secure, sameSite, domain, and maxAge options to reduce client-side exposure. A refresh endpoint verifies the refresh token, issues a new access token, and sets it in a cookie while enforcing token type and signature validation.

When to use it

  • Building authentication for single-page apps, mobile apps, or multi-subdomain sites.
  • When you need server-side session invalidation or per-user session management.
  • To implement secure refresh flows without exposing tokens to JavaScript.
  • When strict cookie controls and HTTPS-only transport are required.
  • To support logout-all-devices and session auditing via Redis.

Best practices

  • Use separate secrets for access and refresh tokens and rotate them per environment.
  • Keep access tokens short-lived (minutes to hours) and refresh tokens longer with rotation policies.
  • Store only non-sensitive identifiers in tokens; keep user-sensitive state in server-side storage.
  • Enforce HTTPS and set cookie flags: httpOnly, secure, sameSite=strict (or lax when needed).
  • Validate token signatures and token type on every protected endpoint and refresh flow.

Example use cases

  • Issuing access/refresh cookies for a React SPA hosted across subdomains.
  • Invalidating all sessions after password reset by deleting Redis user session hashes.
  • Refreshing access tokens transparently via a secure refresh endpoint that sets an httpOnly cookie.
  • Maintaining session metadata (device, createdAt) in Redis for audit and UI session management.
  • Implementing logout that deletes the Redis session entry and clears cookies.

FAQ

Should I store user data in JWT payload?

No. Store only identifiers and non-sensitive claims in tokens; keep sensitive or mutable data in Redis or your database.

How often should I rotate secrets?

Rotate secrets regularly and have a key versioning strategy; ensure refresh tokens are revoked after rotation or implement backward-compatible validation windows.