tsndr / cloudflare-worker-jwt

A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
MIT License
680 stars 55 forks source link

Expired or wrong signature? #11

Closed POD666 closed 2 years ago

POD666 commented 2 years ago

I need to know exactly why a token failed verification.

Using the jwt.verify function I don't know the reason as it might be expired or wrongly signed.

So I have implemented the following workaround:

let validationMessage = "ok";
let isValid = false;
try {
  isValid = await jwt.verify(token, SECRET);
  if (!isValid) {
    if (jwtClaims.exp < Math.floor(Date.now() / 1000)) {
      throw new Error('token expired')
    }
    throw new Error('wrong signature')
  }
} catch (error) {
  validationMessage = `jwt verify failed: ${error.message}`;
}

I would like to suggest throwing such errors from jwt.verify and only returning true in case of success (never return false).

I could prepare PR but it's a breaking change, so I'm not sure if you accept it.

Maybe as a separate verify_unsafe function or add a boolean thow=false flag to the existing func?

What do you think?

tsndr commented 2 years ago

Hey, you're not the first person asking me about this, but I didn't want to introduce breaking changes so I didn't implement it yet.

defudef commented 2 years ago

I think, adding an optional flag (false by default) wouldn't introduce breaking changes and could level up the developer experience for sure.

jwt.verify(token, SECRET) // returns boolean. "throwError" flag set as false by default
jwt.verify(token, SECRET, { throwError: true }) // returns true or throws an error (data type still the same)

I can raise a PR if you're happy with that.

tsndr commented 2 years ago

https://github.com/tsndr/cloudflare-worker-jwt/tree/v1.2.0

We happy now? 😉

POD666 commented 2 years ago

Awesome!

Maybe readme could be a bit improved:

image
tsndr commented 2 years ago

I know, feel free to make a PR if you like to clean up the readme, otherwise I'll do it eventually.