Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 277 Vote(s) - 3.56 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Authenticating the request header with Express

#1
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?
Reply

#2
That's what [middleware](

[To see links please register here]

) 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.
Reply

#3
```
const token = req.headers.authorization.split(' ')[1];
if(!token) return res.send("No credentials");
// next(); // Let the user proceed
```
Reply

#4
Here is a solution with a more modular approach to chain validations, creating a middleware with a validator library specifically designed for express: [express-validator][1].

Example of expected header `Authorization: Bearer c8f27fee2a579fa4c3fa580`

1. Install `express-validator` package:


`npm install --save express-validator` OR `yarn add express-validator`


----------


2. Create a middleware (e.g. in path `src/middlewares/validators.js`)

```javascript
import { header, validationResult } from "express-validator";

export const myRequestHeaders = [
header('authorization')
.exists({ checkFalsy: true })
.withMessage("Missing Authorization Header") // you can specify the message to show if a validation has failed
.bail() // not necessary, but it stops execution if previous validation failed
//you can chain different validation rules
.contains("Bearer")
.withMessage("Authorization Token is not Bearer")
];

export function validateRequest(req, res, next) {
const validationErrors = validationResult(req);
const errorMessages = [];

for (const e of validationErrors.array()) {
errorMessages.push(e.msg);
}

if (!validationErrors.isEmpty()) {
return res.status(403).json({ "errors": errorMessages });
}
next();
}

```


----------


3. use validator middlewares in your endpoint.

**IMPORTANT**: you need use the middlewares before your actual route function. Also, you need to chain the middleware such that the `validateRequest` function (which actually verifies the validity of your request) comes after the expected header validator, in this case `myRequestHeader`. See below:

```javascript
app.use('/api/v1/your-endpoint', myRequestHeaders, validateRequest, async (req, res) => {
// the validator middleware will have already thrown a 403 if the header was missing,
// so you can be 100% sure that the header is present with validations your created.
console.log("req.headers.authorization", req.headers.authorization);

// do whatever you want
const actualToken = getBearerTokenFromHeader(req.headers.authorization); // c8f27fee2a579fa4c3fa580

res.sendStatus(200);
})

// helper function to get token value
const getBearerTokenFromHeader = (authToken) => {
return authToken.split(" ")[1]
}
```


With this library you can check the presence and quality of headers, parameters, body data and so on.

[1]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through