How to Check a JWT's Issuer and Audience in Rust with jsonwebtoken Validation
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
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>)?;
| Part | What 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
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:

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 aValidationthat accepts HS256, the one issuer and the one audience, and requiresexp,issandaud.checkdecodes the token with aValidationand printsacceptedwith the user, orrejectedwith the error.- The last check uses
Validation::new(Algorithm::HS256)as it comes, with no issuer or audience set.
Step 3: Run It
cargo run -q
accepted: sub ada
rejected: InvalidAudience
rejected: InvalidIssuer
rejected: InvalidAudience

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
Validationwith no audience set failed too, withInvalidAudience. The README explains: "In the case ofaud, if there is a value set in the token but not in theValidation, the token will be rejected."validate_audis 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
| Mistake | What happens | Do this instead |
|---|---|---|
| Setting the issuer and audience without making them required | A token without iss or aud passes | Add them with set_required_spec_claims(&["exp", "iss", "aud"]) |
Leaving exp out of set_required_spec_claims | The list replaces the default, so a token without exp passes | List "exp" too |
Turning validate_aud off to get past InvalidAudience | A 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
| Symptom | Likely cause | Fix |
|---|---|---|
InvalidAudience, with no audience set | The token has an aud, and validate_aud is on by default | Call set_audience with your API's audience |
InvalidAudience, with an audience set | The token was made for another API | Check which API the token was made for |
InvalidIssuer | The token comes from another issuer | Use the issuer exactly as the token has it |
Missing required claim: aud | The token has no aud, and aud is required | Have 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
- Validation and decode, on docs.rs.
- Validation, in the jsonwebtoken README.
- RFC 8725 section 3.9: Use and Validate Audience.
