tsndr / cloudflare-worker-jwt

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

Option to verify despite expiry #43

Closed jamesgpearce closed 10 months ago

jamesgpearce commented 11 months ago

I'm considering a pattern where the token is very short lived, so there's an option to revoke it within a short while if needed. In this case I would want to re-issue a token if the previous one was valid but expired (and of course the user has not been banned).

In this case I want to know that it has expired, but that the signature was correct and it would be had the exp not passed. Could this be an option somehow on the verify method? "Valid in signature, though not in time" kind of thing.

Then at least I can be sure which user to go and lookup to see if they've been banned before issuing a new one. Thanks.

tsndr commented 11 months ago

Token Revocation

The best way to revoke a token would probably be to roll your secret.

Expiration Check

Currently there would be two options for checking if the token has expired:

1. Implementing the check yourself

export type JwtPayload = {
    sub: string
}

const token = 'eyJhbG...'

const { payload } = jwt.decode<JwtPayload>(token)

if (payload?.exp < Math.floor(Date.now() / 1000)) {
    // Token expired
}

2. Using throwError

Enabling throwError will throw instead of just returning false.

const token = 'eyJhbG...'

try {
    await jwt.verify(token, 'super secret', { throwError: true })
} catch (error) {
    if (error === 'EXPIRED') {
        // Token expired
    }
}

There's not just EXPIRED, there's also NOT_YET_VALID and PARSE_ERROR.

jamesgpearce commented 11 months ago

Right! But also I want to check that it once WAS validly signed. Because the exp logic throws before the cryptographic verification, I can't distinguish between a token that has been tampered with, and one that has not been tampered with but recently expired.

tsndr commented 11 months ago

Maybe this will help :)

jamesgpearce commented 10 months ago

Awesome. Thank you!