Skip to main content

How to Check a JWT's Issuer and Audience in Rust with jsonwebtoken Validation

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

jsonwebtoken checks a token's issuer and audience when you give its Validation the values you expect, with set_issuer and set_audience. A token without the claims still passes those checks, though, until you add iss and aud to the required claims with set_required_spec_claims.

Syntax​

Syntax
let mut <validation> = Validation::new(<algorithm>);
<validation>.set_issuer(&[<issuer>]);
<validation>.set_audience(&[<audience>]);
<validation>.set_required_spec_claims(&["exp", "iss", "aud"]);

let <data> = decode::<Claims>(<token>, &<key>, &<validation>)?;
PartWhat it does
Validation::new(<algorithm>)The checks decode runs, accepting only <algorithm>.
set_issuer(&[<issuer>])The issuers you accept. The token's iss must be one of them.
set_audience(&[<audience>])The audiences you accept. The token's aud must be one of them.
set_required_spec_claims(...)The claims a token must have. It replaces the default list, which holds only exp.
decode::<Claims>(...)Checks the signature and the claims, and reads them into your Claims struct.
<data>The token's header and claims, when every check passed.

The jsonwebtoken documentation for Validation describes iss as "a collection of one or more acceptable issuers members", and adds about it: "Validation only happens if iss claim is present in the token. Adding iss to required_spec_claims will make it required." It says the same about aud. Of required_spec_claims, it says: "Defaults to {"exp"}".

The Example​

The example signs a token issued by https://login.example.org for https://photos.example.org. It decodes it four times: with the right issuer and audience, with the audience of another API, with another issuer, and with a Validation that has no audience set.

Prerequisites​

  • Rust, with Cargo. This guide uses Rust 1.100.1.

Step 1: Create the Project​

Terminal
cargo new demo
cd demo
cargo add jsonwebtoken --features rust_crypto
cargo add serde --features derive

cargo new demo creates the project. jsonwebtoken, version 12.0.0 here, needs a cryptography backend chosen by a feature, here rust_crypto, and serde's derive feature lets the claims struct turn into JSON and back.

Step 2: Write the Code​

Replace the contents of src/main.rs:

src/main.rs, with a check function that decodes a token and prints accepted or rejected, an expecting function that builds a Validation with set_issuer, set_audience and set_required_spec_claims, and a main that signs a token and checks it four times.

src/main.rs
use std::time::{SystemTime, UNIX_EPOCH};

use jsonwebtoken::errors::Error;
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Claims {
iss: String,
sub: String,
aud: String,
exp: u64,
}

/// Decodes token with validation and says what happened.
fn check(token: &str, key: &DecodingKey, validation: &Validation) {
match decode::<Claims>(token, key, validation) {
Ok(data) => println!("accepted: sub {}", data.claims.sub),
Err(err) => println!("rejected: {err}"),
}
}

/// A validation that expects the given issuer and audience.
fn expecting(issuer: &str, audience: &str) -> Validation {
let mut validation = Validation::new(Algorithm::HS256);
validation.set_issuer(&[issuer]);
validation.set_audience(&[audience]);
validation.set_required_spec_claims(&["exp", "iss", "aud"]);
validation
}

fn main() -> Result<(), Error> {
// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
let secret = "C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=";
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("the clock is set before 1970")
.as_secs();
let claims = Claims {
iss: "https://login.example.org".to_owned(),
sub: "ada".to_owned(),
aud: "https://photos.example.org".to_owned(),
exp: now + 2 * 60 * 60,
};
let token = encode(
&Header::new(Algorithm::HS256),
&claims,
&EncodingKey::from_base64_secret(secret)?,
)?;
let key = DecodingKey::from_base64_secret(secret)?;

let right = expecting("https://login.example.org", "https://photos.example.org");
let wrong_audience = expecting("https://login.example.org", "https://videos.example.org");
let wrong_issuer = expecting("https://other.example.org", "https://photos.example.org");
check(&token, &key, &right);
check(&token, &key, &wrong_audience);
check(&token, &key, &wrong_issuer);
check(&token, &key, &Validation::new(Algorithm::HS256));
Ok(())
}
  • expecting(issuer, audience) builds a Validation that accepts HS256, the one issuer and the one audience, and requires exp, iss and aud.
  • check decodes the token with a Validation and prints accepted with the user, or rejected with the error.
  • The last check uses Validation::new(Algorithm::HS256) as it comes, with no issuer or audience set.

Step 3: Run It​

Terminal
cargo run -q
Output
accepted: sub ada
rejected: InvalidAudience
rejected: InvalidIssuer
rejected: InvalidAudience

A zsh terminal where cargo run prints accepted sub ada, then rejected InvalidAudience, rejected InvalidIssuer, and rejected InvalidAudience again.

The command is the same in zsh, bash and PowerShell.

What Happened​

  • The right issuer and audience passed.
  • The videos audience failed with InvalidAudience.
  • Another issuer failed with InvalidIssuer.
  • The Validation with no audience set failed too, with InvalidAudience. The README explains: "In the case of aud, if there is a value set in the token but not in the Validation, the token will be rejected." validate_aud is on by default.

The required claims matter as much as the expected values. With set_issuer and set_audience but the default required claims, a token without aud passed, and so did one without iss. With iss and aud in set_required_spec_claims, they were rejected with Missing required claim: aud and Missing required claim: iss.

Common Mistakes​

MistakeWhat happensDo this instead
Setting the issuer and audience without making them requiredA token without iss or aud passesAdd them with set_required_spec_claims(&["exp", "iss", "aud"])
Leaving exp out of set_required_spec_claimsThe list replaces the default, so a token without exp passesList "exp" too
Turning validate_aud off to get past InvalidAudienceA token made for any API passes. The documentation calls it "Very insecure to turn this off"Set your API's audience with set_audience

Troubleshooting​

SymptomLikely causeFix
InvalidAudience, with no audience setThe token has an aud, and validate_aud is on by defaultCall set_audience with your API's audience
InvalidAudience, with an audience setThe token was made for another APICheck which API the token was made for
InvalidIssuerThe token comes from another issuerUse the issuer exactly as the token has it
Missing required claim: audThe token has no aud, and aud is requiredHave the sign-in service set an audience

FAQ​

How do I tell a wrong audience from other failures in code?​

Call kind() on the error. It returns an ErrorKind, which was InvalidAudience and InvalidIssuer for the failures above, and MissingRequiredClaim("aud") for a token without aud.

Can I accept several issuers or audiences?​

Yes. Pass them all, as in set_audience(&["https://photos.example.org", "https://videos.example.org"]). A token for the videos API passed that check.

Conclusion​

Give the Validation your issuer and audience with set_issuer and set_audience, and make both claims required with set_required_spec_claims(&["exp", "iss", "aud"]). jsonwebtoken then rejects tokens from other issuers, tokens made for other APIs and tokens without the claims.

Additional Resources​