Zander Fick
Zander Fick

Reputation: 116

How to deserialize JWT with "http://url/path" as field names?

I have an actix-web server that will be validating a JWT with each request and extracting claims for internal use. I have the JWT decode-and-validate process working, based on this example by Auth0.

The problem I have is the enterprise application I need to work with has its claims structured as:

{
    "https://some-org-url/domain": "some-domain",
    "https://some-org-url/roles": [
        "...",
    ],
    "https://some-org-url/tag-list": [
        "...",
    ],
    "iss": "https://auth-app.com/",
    "sub": "app|xxxxxxxxxxx",
    "aud": [
        "https://some-org-url",
        "https://auth-app.com/userinfo"
    ],
    "iat": 1660117559,
    "exp": 1660203959,
    "azp": "xxxxxxxxx",
    "scope": "openid profile email"
}

I can extract the syntactically valid claims by defining my struct as

#[derive(Debug, Deserialize)]
pub struct Claims {
    iss: String,
    sub: String,
    aud: Vec<String>,
    iat: u32,
    exp: u32,
    azp: String,
    scope: String
}

But I am failing to find a way to extract the remaining claims:

i.e. the arbitrary claims that cannot be defined as struct fields as-is. Using their path stems (e.g. domain or roles) does not work. Any suggestions?

Upvotes: 1

Views: 158

Answers (1)

Zander Fick
Zander Fick

Reputation: 116

After stepping throuh jsonwebtoken::decode a few times, I realised that it calls Deserialize on the Claims struct you define, passing in the JWT body as data, therefore you can leverage serde field aliases to achieve the desired outcome:

#[derive(Debug, Deserialize)]
pub struct Claims {
    #[serde(alias = "https://some-org-url/domain")]
    domain: String,

    #[serde(alias = "https://some-org-url/roles")]
    roles: Vec<String>,

    #[serde(alias = "https://some-org-url/tag-list")]
    tag_list: Vec<String>,

    iss: String,
    sub: String,
    aud: Vec<String>,
    iat: u32,
    exp: u32,
    azp: String,
    scope: String
}

- which works fine.

Upvotes: 1

Related Questions