Skip to content

Security & Authentication Middleware

DyneMCP provides a unified authentication middleware for securing your MCP server. This middleware supports JWT, OAuth2/OIDC, or both, and is designed to be easy to configure and production-ready.

The recommended way to secure your DyneMCP server is to use the dynemcpMiddleware from @dynemcp/dynemcp/server/api/auth/dynemcp-middleware.

import {
dynemcpMiddleware,
type DynemcpMiddlewareConfig,
} from '@dynemcp/dynemcp/server/api/auth/dynemcp-middleware'
// JWT authentication (simple)
export default dynemcpMiddleware({
type: 'jwt',
jwt: {
secret: process.env.JWT_SECRET!,
allowedRoles: ['admin', 'user'], // optional
expectedAudience: 'your-api', // optional but recommended
},
})
export default dynemcpMiddleware({
type: 'oauth2',
oauth2: {
issuerBaseURL: process.env.AUTH0_ISSUER_URL!,
audience: process.env.AUTH0_AUDIENCE!,
},
})
export default dynemcpMiddleware({
type: 'both',
jwt: {
secret: process.env.JWT_SECRET!,
allowedRoles: ['admin'],
},
oauth2: {
issuerBaseURL: process.env.AUTH0_ISSUER_URL!,
audience: process.env.AUTH0_AUDIENCE!,
},
})
  • JWT: Use a strong secret and set expectedAudience for production security.
  • OAuth2: Use your provider’s issuer URL and audience.
  • Both: The middleware will try OAuth2 first, then fallback to JWT.
  • The middleware sets req.user to the decoded token payload if valid.
  • If authentication fails, the server responds with 401 or 403 as appropriate.

See the default-http template for a real-world example.