Creates an Express middleware function to authenticate a user using a JWT token.
This middleware checks the Authorization header for a Bearer token, verifies the token, and checks its audience.
If the token is valid, it attaches the user information (decoded JWT, raw token, and PKP address) to the request object as req.user.
If the token is missing or invalid, it returns a 401 Unauthorized response with an error message.
NOTE: Wrap your route handler functions with authenticatedRequestHandler() to assert the type of Request and to
ensure that req.user was correctly set before your route handler is run.
// In your environment configuration constALLOWED_AUDIENCE = 'https://yourapp.example.com';
// Create the authentication middleware constauthenticateUser = getAuthenticateUserExpressHandler(ALLOWED_AUDIENCE);
// Define a handler that requires authentication constgetProtectedResource = (req: ExpressAuthHelpers['AuthenticatedRequest'], res: Response) => { // The request is now authenticated // No need for type casting as the handler is properly typed const { pkpAddress } = req.user; res.json({ message:`Hello, user with PKP address ${pkpAddress}` }); };
// Apply to routes that require authentication by using authenticatedRequestHandler app.get('/protected-resource', authenticateUser, authenticatedRequestHandler(getProtectedResource));
You can see the source for getAuthenticateUserExpressHandler() below; use this as a reference to implement
your own midddleware/authentication for other frameworks! Pull requests are welcome.
Creates an Express middleware function to authenticate a user using a JWT token.
This middleware checks the
Authorization
header for a Bearer token, verifies the token, and checks its audience. If the token is valid, it attaches the user information (decoded JWT, raw token, and PKP address) to the request object asreq.user
. If the token is missing or invalid, it returns a 401 Unauthorized response with an error message.NOTE: Wrap your route handler functions with
authenticatedRequestHandler()
to assert the type ofRequest
and to ensure thatreq.user
was correctly set before your route handler is run.See express.js documentation for details on writing your route handler
Example
You can see the source for
getAuthenticateUserExpressHandler()
below; use this as a reference to implement your own midddleware/authentication for other frameworks! Pull requests are welcome.