0

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.

Matt Saunders
  • 3,538
  • 2
  • 22
  • 30

1 Answers1

0

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:

  • Your POST request must include a GraphQL query to authenticate your user against
  • CORS options must be properly configured
  • A sessionStore must also be provided - see here
Matt Saunders
  • 3,538
  • 2
  • 22
  • 30