Search code examples
rustjwtserde

Rust JWT claim not valid struct field name


I'm trying to generate some JWTs using the following https://github.com/Keats/jsonwebtoken crate. Basically, I have

#[derive(Debug, Serialize, Deserialize)]
struct MyTokenClaims {
    foo: String,
    bar: String,
    baz: String,
}

Now the problem is that in the JWT the claim foo would actually be example.com/foo. Is there a way to override the field name in the JWT that is used after encoding it, since I can't create a struct field with that name?


Solution

  • In serde you can alias the field name:

    #[derive(Debug, Serialize, Deserialize)]
    struct MyTokenClaims {
       #[serde(rename(serialize = "example.com/foo", deserialize = "example.com/foo"))]
        foo: String,
        bar: String,
        baz: String,
    }
    

    When reading JSON, your code now looks for the field "example.com/foo": "value" and serialises the value in rust to foo: "value".