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?
The HTTP Authorization request header can be used to provide credentials that authenticate a user agent with a server, allowing access to a protected resource. The Authorization header is usually, but not always, sent after the user agent first attempts to request a protected resource without credentials.
To send a GET request with a Bearer Token authorization header, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.
In the URL field enter the address to the users route of your local API - http://localhost:4000/users . Select the "Authorization" tab below the URL field, change the type to "Basic Auth" in the type dropdown selector, enter test into the "Username" field and test into the "Password" field.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With