Keats / jsonwebtoken

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

Document that "exp" field is required #354

Open dricair opened 6 months ago

dricair commented 6 months ago

I tried to implement tests containing the code present in the doc for encode and decode.

But it triggers an error because "exp" claim is missing. It took me quite some time to understand that we need to explicitly add this field to the Claim structure. I think the doc should be updated to show it. Something like this for encode:

use serde::{Deserialize, Serialize};
use jsonwebtoken::{encode, Algorithm, Header, EncodingKey, get_current_timestamp};

#[derive(Debug, Serialize, Deserialize)]
struct Claims {
   sub: String,
   company: String,
   exp: i64
}

let my_claims = Claims {
    sub: "b@b.com".to_owned(),
    company: "ACME".to_owned(),
    // 5 minutes validity
    exp: get_current_timestamp() + 300
};

// my_claims is a struct that implements Serialize
// This will create a JWT using HS256 as algorithm
let token = encode(&Header::default(), &my_claims, &EncodingKey::from_secret("secret".as_ref())).unwrap();
Keats commented 6 months ago

It's required if you don't turn it off in the https://docs.rs/jsonwebtoken/latest/jsonwebtoken/struct.Validation.html struct

dricair commented 6 months ago

Yes I agree, but it would be a lot easier to show it in the example, as it's only when testing that it tells it is required.