简体   繁体   中英

Inserting password reset token to unprotected NodeJS route

I am currently trying to pass my password reset generated token inside my unprotected route but whenever I execute my GET request, I receive an 401 Unauthorized request .

I've tried including the package Path-to-RegExp and constructing a separate array route but it didn't work:

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

My password-reset token is generated in a separated service and called in a controller:

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

Here is how I've structured my expressJwt with unless :

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

     MY TOKEN AUTHORISATION CODE IS PLACED HERE.
 }

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

My issue is that whenever I try to create a unauthenticated route such as .unless({path: ['/images/', '/user/password-reset', '/user/reset/:token' ]})); the route /user/reset/:token is only parsed as a string a the value of :token is not actually passed.

I've read some similar questions about passing it with regex or functions but I couldn't figure it out myself. This and this question have been particularly useful on how to approach the problem.

You can pass a regex to unless, which you may have already realized since you tried to use Path-to-RegExp. You could also just try to write the regex yourself and pass it directly to unless. In your case your unless would look like this:

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

EDIT: this SO answer suggest that you cannot combine regex and strings in the same array, so I've converted all paths to regex expressions.

You have an array within an array for the value of path passed into unless .

Change:

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

To:

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

And change unprotected to include the other paths:

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

Ensure you test with a path that includes a token eg: /user/reset/123-some-real-looking-value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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