import { createVincentUserMiddleware } from '@lit-protocol/vincent-app-sdk/expressMiddleware';
// In your environment configuration
const ALLOWED_AUDIENCE = 'https://yourapp.example.com';
const VINCENT_APP_ID = 555; // Provided by the vincent app registry
const { middleware, handler } = createVincentUserMiddleware({
allowedAudience: ALLOWED_AUDIENCE,
requiredAppId: VINCENT_APP_ID,
userKey: 'vincentUser',
});
// Apply to routes that require authentication; req is guaranteed authenticated because it is wrapped in `handler()`
app.get('/protected-resource', middleware, handler((req, res) => {
// handler() gives you the correct inferred type of `req[userKey]`
const pkpAddress = req.vincentUser.decodedJWT.payload.pkp.ethAddress;
const appInfo = req.vincentUser.decodedJWT.payload.app;
if(appInfo) {
res.json({ message: `Hello, user with PKP address ${pkpAddress}. You are authenticated for app ${appInfo.id} @ v${appInfo.version}` });
return;
}
res.json({ message: `Hello, user with PKP address ${pkpAddress}.` });
})
);
See the code below for the implementation used by the middleware
returned by this function. You can adapt this logic
to the HTTP framework of your choice.
Returns an Express middleware function to authenticate a user using a JWT token, and a type-guard wrapper function for type-safe usage of route handlers guarded by the middleware.
The
middleware()
function:Authorization
header for a Bearer token, verifies the token, and checks its audience.Designate what field on
req
should be set with the JWT with theuserKey
configuration option.The
handler()
function:req
where theuserKey
you have provided is correctly inferred to the appropriate typemiddleware
somewhere in the chain before you use thehandler()
handler()
function will throw an error if the expectedreq[userKey]
does not exist.See express.js documentation for details on writing your route handler