简体   繁体   English

使用 Express 验证请求 header

[英]Authenticating the request header with Express

I want to verify that all our get requests have a specific token in their authentication header.我想验证我们所有的 get 请求在其身份验证 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?有没有更好的方法在不更改每个端点的情况下在 NodeJS/Express 中处理这个问题? something like a before-filter/AOP approach?类似于前置过滤器/AOP 方法?

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. 确保在应用中间件的路由之前声明中间件。

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

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 .这是一个采用更加模块化的链式验证方法的解决方案,它创建了一个带有专门为 express 设计的验证器库的中间件: express-validator

Example of expected header Authorization: Bearer c8f27fee2a579fa4c3fa580预期示例 header Authorization: Bearer c8f27fee2a579fa4c3fa580

  1. Install express-validator package:安装express-validator package:

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


  1. Create a middleware (eg in path src/middlewares/validators.js )创建一个中间件(例如在路径src/middlewares/validators.js中)
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();
}


  1. 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 .重要提示:您需要在实际路由 function 之前使用中间件。此外,您需要链接中间件,以便validateRequest function(实际上验证您的请求的有效性)出现在预期的 header 验证器之后,在本例中为myRequestHeader See below:见下文:

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.使用此库,您可以检查标头、参数、正文数据等的存在和质量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM