Keats / jsonwebtoken

JWT lib in rust
MIT License
1.67k stars 266 forks source link

Validate token from JWK Set #285

Closed nick9822 closed 1 year ago

nick9822 commented 1 year ago

Ability to verify token from JWK Set. It is useful in an environment where there are multiple rotating keys per algorithm.

pub fn decode_from_jwks<T: DeserializeOwned>(
    token: &str,
    jwks: &Vec<Jwk>,
) -> Result<TokenData<T>> {
    ...
}

// API to use like
decode_from_jwks::<Claims>(&token, &jwks)

Please let me know your thoughts. Happy to contribute.

Keats commented 1 year ago

There's https://docs.rs/jsonwebtoken/latest/jsonwebtoken/struct.DecodingKey.html#method.from_jwk already

nick9822 commented 1 year ago

@Keats Sorry I meant JWKS, Just updated the issue.

Keats commented 1 year ago

We already have all the types created for JWKS: https://docs.rs/jsonwebtoken/latest/jsonwebtoken/jwk/index.html so you can just deserialize your payload easily, after that you can get the right JWK with https://docs.rs/jsonwebtoken/latest/jsonwebtoken/jwk/struct.JwkSet.html and last the DecodingKey::from_jwk.

I think I'd rather keep the plumbing of the various bits up to the crate user rather than having a function for that.

nick9822 commented 1 year ago

@Keats Got it. One thing I noticed when parsing JWKS, if the JWKS contains an algorithm that this library does not support the deserializing errors out. Like in my case I am getting JWKS from a url, it's not feasible/efficient for me to modify the response before desdeserializing it.

Shouldn't we handle this case? I added the other variant and it's working now with my fork.

Keats commented 1 year ago

What was the variant missing?

nick9822 commented 1 year ago

RSA-OAEP

Keats commented 1 year ago

And it validates fine with this crate? I only allow the algorithm explicitly supported by this crate in the JWK definition.

nick9822 commented 1 year ago

No, it does not validate. For sign and validate, I am returning errors. In my case there are 5 keys and one of it RSA-OAEP, mostly this alg is not used. But due to the response from jwk uri response, I need to handle it.

nick9822 commented 1 year ago

https://github.com/nick9822/jsonwebtoken/commit/3774b4266e17484bbebc6d0a662848c40cb86ece May be I can create some error as errors::ErrorKind::UnimplementedAlgorithm

Keats commented 1 year ago

I think the current behaviour is fine then. I don't want to add some catch all fields in the Algorithm enums and it's either that or not using the Algorithm enum in the JWK which would lose some valuable info.

nick9822 commented 1 year ago

Sure but skipping Other variant from deserialization works in our use case. Luckily rust also let us think of the exhaustiveness so sign and verify are protected. Anyways thank you for looking into it.