Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authenticating the request header with Express

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?

like image 683
kambi Avatar asked Sep 07 '17 10:09

kambi


People also ask

What is req headers authorization?

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.

How do I pass the authorization header in GET request?

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.

How do I pass the authorization header in node JS?

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.


1 Answers

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.

like image 114
robertklep Avatar answered Oct 10 '22 11:10

robertklep