【问题标题】:Inserting password reset token to unprotected NodeJS route将密码重置令牌插入未受保护的 NodeJS 路由
【发布时间】:2019-09-02 05:16:18
【问题描述】:

我目前正尝试在我的 unprotected 路由中传递我的密码重置生成的令牌,但是每当我执行我的 GET 请求时,我都会收到一个401 Unauthorized request

我尝试包含包 Path-to-RegExp 并构造一个单独的数组路由,但它不起作用:

let tokens = [];
const unprotected = [
  pathToRegexp('/user/reset/:token', tokens),
];

我的 password-reset 令牌在单独的服务中生成并在控制器中调用:

 const token = crypto.randomBytes(20).toString('hex');
          user.update({
            resetPasswordToken: token,
            resetPasswordExpires: Date.now() + 360000,
          });

这是我使用unless 构建expressJwt 的方式:

app.use(expressJwt({
  secret: process.env.SECRET_BEARER,
  getToken: req => {

     MY TOKEN AUTHORISATION CODE IS PLACED HERE.
 }

}).unless({ path: ['/images/', '/user/password-reset', unprotected ]}));

我的问题是,每当我尝试创建未经身份验证的路由(例如 .unless({path: ['/images/', '/user/password-reset', '/user/reset/:token' ]}));)时,路由 /user/reset/:token 仅被解析为字符串,而 :token 的值实际上并未传递。

我已经阅读了一些关于使用正则表达式或函数传递它的类似问题,但我自己无法弄清楚。 Thisthis 问题对于如何解决问题特别有用。

【问题讨论】:

  • tokensunprotected 如果你console.log 他们有什么价值?
  • [ /^\/user\/reset\/([^\/]+?)(?:\/)?$/i ] [ { name: 'token', prefix: ' /',分隔符:'/',可选:false,重复:false,模式:'[^\\/]+?' } ]

标签: javascript node.js regex express authentication


【解决方案1】:

您可以将正则表达式传递给除非,因为您尝试使用 Path-to-RegExp 时可能已经意识到这一点。您也可以尝试自己编写正则表达式并将其直接传递给除非。在你的情况下,你的除非看起来像这样:

.unless({ path: [/\/images\//, /\/user\/password-reset\//, /^\/user\/reset\/[a-z0-9_-]*/]}));

编辑: SO answer 建议您不能将正则表达式和字符串组合在同一个数组中,因此我已将所有路径转换为正则表达式。

【讨论】:

  • 由于某种原因,它现在返回一个404,我不认为这是正确匹配的。
  • @someonewithakeyboard 您请求的确切路径是什么?
  • 我需要传递/user/reset/:token,其中:token 是我的密码重置令牌的值..
  • @someonewithakeyboard 是带有可能短划线和下划线的字母数字标记吗?如果是这样,请参阅我的更新答案
  • 是的,我已经尝试过了,但我一直收到404,它指向"http://localhost:3003/user/reset/" + tokenURL
【解决方案2】:

您有一个数组中的数组,用于将path 的值传递给unless

变化:

}).unless({ path: ['/images/', '/user/password-reset', unprotected ]}));

收件人:

}).unless({ path: unprotected }));

并更改 unprotected 以包含其他路径:

const unprotected = [
  '/images/',
  '/user/password-reset',
  pathToRegexp('/user/reset/:token', tokens),
];

确保使用包含令牌的路径进行测试,例如: /user/reset/123-some-real-looking-value

【讨论】:

  • 感谢您花时间帮助我,不幸的是,这根本不起作用。我的构建失败了
  • “我的构建失败”没有帮助,请编辑您的问题以提供完整的简化代码示例和构建错误。
猜你喜欢
  • 1970-01-01
  • 2019-11-22
  • 2020-08-21
  • 1970-01-01
  • 2011-12-23
  • 2021-11-04
  • 2016-01-21
  • 2013-04-08
  • 2022-11-16
相关资源
最近更新 更多