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.
How to Use the Middleware
Section titled “How to Use the Middleware”The recommended way to secure your DyneMCP server is to use the dynemcpMiddleware
from @dynemcp/dynemcp/server/api/auth/dynemcp-middleware
.
Example: Using in middleware.ts
Section titled “Example: Using in middleware.ts”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 },})
Example: OAuth2/OIDC Authentication
Section titled “Example: OAuth2/OIDC Authentication”export default dynemcpMiddleware({ type: 'oauth2', oauth2: { issuerBaseURL: process.env.AUTH0_ISSUER_URL!, audience: process.env.AUTH0_AUDIENCE!, },})
Example: Both JWT and OAuth2 (Composite)
Section titled “Example: Both JWT and OAuth2 (Composite)”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.