Authenticating the request header with Express

59,143

That's what middleware is for:

app.use(function(req, res, next) {
  if (!req.headers.authorization) {
    return res.status(403).json({ error: 'No credentials sent!' });
  }
  next();
});

...all your protected routes...

Make sure that the middleware is declared before the routes to which the middleware should apply.

Share:
59,143
kambi
Author by

kambi

Updated on April 16, 2020

Comments

  • kambi
    kambi about 4 years

    I want to verify that all our get requests have a specific token in their authentication header.

    I can add this to our get endpoints:

    app.get('/events/country', function(req, res) {
        if (!req.headers.authorization) {
        return res.json({ error: 'No credentials sent!' });
        }
    

    Is there any better way to handle this in NodeJS/Express without changing every endpoint? something like a before-filter/AOP approach?

  • Bo Lu
    Bo Lu about 5 years
    to get the request header, recommended way is req.get('authorization')
  • robertklep
    robertklep about 5 years
    @BoLu recommended by whom?
  • Bo Lu
    Bo Lu about 5 years
    it is in the Express official doc
  • robertklep
    robertklep about 5 years
    @BoLu but it doesn't say anywhere that using req.get is recommended. The same documentation also states that "The req object is an enhanced version of Node’s own request object and supports all built-in fields and methods", so I don't see a reason why someone shouldn't be using req.headers.
  • Bo Lu
    Bo Lu about 5 years
    True, you can use req.headers. But here we're talking about Express and req.get just appears at the top level of its document, so it should be the idiomatic way to get request headers when using Express.
  • Philip Kirkbride
    Philip Kirkbride about 5 years
    I want to use this but it messes up the catch-all 404 I have at the bottom of my script stackoverflow.com/questions/11500204/…
  • robertklep
    robertklep about 5 years
    @PhilipKirkbride in that case, add the proposed middleware separately to each route that needs to be protected (app.use('/protected', auth_middleware, handler)). Alternatively, you can prefix the routes that need to be protected and use a separate express.Router (app.use('/protected', auth_middleware, router)) (example here).
  • Philip Kirkbride
    Philip Kirkbride about 5 years
    @robertklep thanks, writing a middleware function was easier than I expected!
  • Seph Reed
    Seph Reed about 4 years
    For those using typescript, please don't use the req.get(item: string) suggestion for anything. It can not be inspected, it won't return proper types, and -- in general -- using string ids offer zero feedback when debugging.
  • Seph Reed
    Seph Reed over 2 years
    A year later, I'm at this problem again from a different side. req.get() is case insensitive, and that can sometimes save you from confusing errors.