Zaubrik / djwt

Create and verify JSON Web Tokens (JWT) with Deno or the browser.
MIT License
225 stars 23 forks source link

How to access payload's iss on 1.0.0 on validateJwt() ? #16

Closed Frenzoid closed 4 years ago

Frenzoid commented 4 years ago

Hello, im new and not used to this library, and im trying to port from djwt 0.9.0 to 1.0.0.

On 0.9.0 i could use validateJwt to get the payload and therefore the iss data stored there as the following:

const data = await validateJwt(
    jwt,
    secret,
    { isThrowing: false},
  );

console.log(data.payload.iss);

but now i can't, and i can't find any updated example on the docs.

How can i access the iss data from a decripted jwt token on 1.0.0? Sorry for any inconvenience.

Best regards!

marcomaisel commented 4 years ago

Hi @Frenzoid It seems like the validateJwt function had breaking changes rom 0.9.0 to 1.0.0.

Instead of { isThrowing: false} you now need to specify the algorithm { algorithm: "HS256" }

As the documentation states "The function validateJwt returns a promise. This promise resolves to an object with a union type where the boolean property isValid serves as discriminant." This means you need to check if the JWT is valid to get access to the payload.

const data = await validateJwt(
    jwt,
    secret,
    { algorithm: "HS256" },
  );

if (data.isValid) {
    console.log(data.payload.iss);
}
Frenzoid commented 4 years ago

Ooooh i see, so i need to check if it's valid to actually get access to the payload.

Perfect, thanks a lot! and sorry for this noobish question ^^

Best regards!

eolinlovecraft commented 4 years ago

Hi, I am using the version 1.2 and I have the same issue. I have applied the @marcomaisel response but the compiler say

error: TS2531 [ERROR]: Object is possibly 'null'.
                console.log(validation.payload.iss)
                            ~~~~~~~~~~~~~~~~~~
    at file:///....../resolvers/user.ts:21:29

TS2339 [ERROR]: Property 'iss' does not exist on type 'string | number | boolean | PayloadObject | JsonArray'.
  Property 'iss' does not exist on type 'string'.
                console.log(validation.payload.iss)
                                               ~~~
    at file:///...../resolvers/user.ts:21:48

Found 2 errors.

my code is:

const validation: JwtValidation  = await validateJwt({
                jwt: context.ck.get('JWT'),
                key: JWT_SECRET,
                algorithm: JWT_ALGORITHM as Algorithm,
            })

if (validation.isValid) {
                console.log(validation)
                console.log(validation.payload)
                console.log(validation.payload.iss)   <<<< this is the line 21
            }

thanks for the help

marcomaisel commented 4 years ago

Have a look at issue #25. The suggested solution should fix your problem, too.

eolinlovecraft commented 4 years ago

Have a look at issue #25. The suggested solution should fix your problem, too.

works fine. thanks a lot.