Keats / jsonwebtoken

JWT lib in rust
MIT License
1.61k stars 253 forks source link

Make family public #351

Open brymko opened 7 months ago

brymko commented 7 months ago

A patch to hopefully fix all the AlgorithmFamily confusion. We ran into a very similar issue which i think are many describing here. But i noticed that we specifically like to pin the validation of the jwt to the decoding/encoding key that is being used. But unfortunately this is currently not possible without adding more state tracking for our keys, which is annoying given that they already store this information.

This patch will publicize a method to get the AlgorithmFamily from both encoding & decoding key. And also adds a method to AlgorithmFamily that will return a list of all algorithms which are part of the family

Keats commented 7 months ago

Can you add a snippet of how you would use that?

brymko commented 7 months ago

We're using the following primitives to setup correct validation and encoding parameters based on the key given:

fn validation_from_decoding_key(key: &jsonwebtoken::DecodingKey) -> jsonwebtoken::Validation {
    let mut ret = jsonwebtoken::Validation::default();

    ret.algorithms = key.family().algorithms().to_vec();

    ret
}

fn header_from_encoding_key(key: &jsonwebtoken::EncodingKey) -> jsonwebtoken::Header {
    jsonwebtoken::Header {
        alg: *key
            .family()
            .algorithms()
            .first()
            .expect("No algorithms found there must be atleast one algorithm per family"),
        ..jsonwebtoken::Header::default()
    }
}