使用 Express 对请求标头进行身份验证 [英] Authenticating the request header with Express

查看:28
本文介绍了使用 Express 对请求标头进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证我们所有的 get 请求在其身份验证标头中是否都有特定的令牌.

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!' });
    }

有没有更好的方法在 NodeJS/Express 中处理这个而不改变每个端点?类似于前置过滤器/AOP 方法?

Is there any better way to handle this in NodeJS/Express without changing every endpoint? something like a before-filter/AOP approach?

推荐答案

这就是 middleware 用于:

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.

这篇关于使用 Express 对请求标头进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆