tsndr / cloudflare-worker-jwt

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

Cannot verify tokens. #30

Closed Eusebiotrigo closed 1 year ago

Eusebiotrigo commented 1 year ago

Hi, thanks for the library!

I have been trying to verify tokens, and I don't know the reason why the signed tokens are always invalid, verify returns false.

I checked with the example code and verify is returning false.

I am using wrangler 2.6.1 and the 2.1.3 version of this library.

const token = await jwt.sign(
      {
        name: "John Doe",
        email: "john.doe@gmail.com",
        nbf: Math.floor(Date.now() / 1000) + 60 * 60, // Not before: Now + 1h
        exp: Math.floor(Date.now() / 1000) + 2 * (60 * 60), // Expires: Now + 2h
      },
      "secret"
    );

    // Verifying token
    const isValid = await jwt.verify(token, "secret"); // false

The token generated is:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiSm9obiBEb2UiLCJlbWFpbCI6ImpvaG4uZG9lQGdtYWlsLmNvbSIsIm5iZiI6MTY3MDUwMjAyNSwiZXhwIjoxNjcwNTA1NjI1LCJpYXQiOjE2NzA0OTg0MjV9.-UdjUY8GJpaae2WpUTvbLsJQY8FNqVeNQiVDyNH_h0A

And verify returns a false

Eusebiotrigo commented 1 year ago

Could be that I'm stupid and cannot verify a token that is not valid till 1 hour later...

tsndr commented 1 year ago

Look at the comments in the code you posted 🙂

nbf = Now + 1h exp = Now + 2h

So the token will be valid in an hour from now and it will have expired in 2 hours from now.

I added those to the example code trying to convey how it works, maybe I should change it 🤔

Eusebiotrigo commented 1 year ago

No need to change the comments or the examples... But anyway, I'm getting a verify false on my real code. Would you like me to open a new issue?

const access_token = await jwt.sign(
      {
        exp: Math.floor(Date.now() / 1000) + 60 * 60 * 24, // 1 day from now
        iss: "account",
        sub: "access",
        orgId: "ed7938f2-be8b-40d5-950c-0d8577cbb9cc",
      } as JwtPayload,
      "secret",
      { algorithm: "HS512" }
    );

    const isVerified = await jwt.verify(access_token, "secret");

And it does return false on verification.

Eusebiotrigo commented 1 year ago

My key needs 512 bits to sign it. Forget all this. Getting embarrassing.