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.
Author by
kambi
Updated on April 16, 2020Comments
-
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 about 5 yearsto get the request header, recommended way is
req.get('authorization')
-
robertklep about 5 years@BoLu recommended by whom?
-
Bo Lu about 5 yearsit is in the Express official doc
-
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 usingreq.headers
. -
Bo Lu about 5 yearsTrue, you can use
req.headers
. But here we're talking about Express andreq.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 about 5 yearsI 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 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 separateexpress.Router
(app.use('/protected', auth_middleware, router)
) (example here). -
Philip Kirkbride about 5 years@robertklep thanks, writing a middleware function was easier than I expected!
-
Seph Reed about 4 yearsFor 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 over 2 yearsA 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.