node.jsexpresssessionbearer-tokenkeystonejs

Session / token verification in custom KeystoneJS endpoint


I am successfully authenticating user requests to my KeystoneJS API with the approach outlined here.

However I need to add a custom express endpoint to my application, which should only accessible to users with a valid token in their request header (see this previous answer).

I've been digging through the Keystone docs regarding sessions and middleware, but it's not my area of expertise and I can't work out how request tokens are being validated.

How can I validate the token in the authorisation header of a GET request to my custom endpoint? Appreciate this may relate to express and session management rather than Keystone specifically.


Solution

  • Assuming a standard setup, the following can be added to configureExpress (see here) to apply Keystone session middleware to a custom express endpoint:

    app.use('/myEndpoint', keystone._sessionManager.getSessionMiddleware({ keystone }));
    

    Then:

    const whitelist = ['http://localhost:4200'];
    const corsOptions = {
      origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1 || !origin) {
          callback(null, true)
        } else {
          callback(new Error('Not allowed by CORS'))
        }
      }
    }
    
    app.post('/myEndpoint', cors(corsOptions), (req, res) => {
      if (req.user) {
        // User is authorised
        res.send(req.user);
      } else {
        res.status(401).send()
      }
    });
    

    Notes / gotchas:

    Please note this applies to Keystone V5, which is no longer being actively developed. If you are using Keystone V6, check out the answer from Ali!