pub struct JWTClaims<CustomClaims> {
pub issued_at: Option<UnixTimeStamp>,
pub expires_at: Option<UnixTimeStamp>,
pub invalid_before: Option<UnixTimeStamp>,
pub issuer: Option<String>,
pub subject: Option<String>,
pub audiences: Option<Audiences>,
pub jwt_id: Option<String>,
pub nonce: Option<String>,
pub custom: CustomClaims,
}Expand description
A set of JWT claims that can include both standard JWT claims and custom application-specific data.
This struct represents the payload of a JWT token, containing standard registered claims defined in the JWT specification (RFC 7519) as well as optional custom claims.
The CustomClaims generic parameter allows for including application-specific data:
- Use
NoCustomClaimsif you only need the standard JWT claims - Use your own type that implements
SerializeandDeserializefor custom claims
§Standard Claims
iss(Issuer): Identifies the principal that issued the JWTsub(Subject): Identifies the principal that is the subject of the JWTaud(Audience): Identifies the recipients the JWT is intended forexp(Expiration Time): Identifies the time after which the JWT expiresnbf(Not Before): Identifies the time before which the JWT must not be acceptediat(Issued At): Identifies the time at which the JWT was issuedjti(JWT ID): Provides a unique identifier for the JWT
Plus additional non-standard but commonly used claims:
kid(Key ID): Identifier for the key used to sign the tokennonce: Random value that can be used to prevent replay attacks
§Example
use jwt_simple::prelude::*;
use serde::{Serialize, Deserialize};
// Using only standard claims
let std_claims = Claims::create(Duration::from_hours(1))
.with_issuer("auth.example.com")
.with_subject("user123");
// Using custom claims
#[derive(Serialize, Deserialize)]
struct UserClaims {
user_id: u64,
is_admin: bool,
}
let custom_claims = Claims::with_custom_claims(
UserClaims { user_id: 42, is_admin: false },
Duration::from_hours(1)
).with_issuer("auth.example.com");Fields§
§issued_at: Option<UnixTimeStamp>The “Issued At” (iat) claim - identifies the time at which the JWT was issued.
This claim can be used to determine the age of the token. It is represented as the number of seconds from 1970-01-01T00:00:00Z UTC (the UNIX epoch).
This field is automatically set when using Claims::create() or
Claims::with_custom_claims() to the current time.
expires_at: Option<UnixTimeStamp>The “Expiration Time” (exp) claim - identifies the expiration time of the token.
This claim specifies the time after which the JWT must not be accepted for processing. It is represented as the number of seconds from 1970-01-01T00:00:00Z UTC (the UNIX epoch).
This field is automatically set when using Claims::create() or
Claims::with_custom_claims() to the current time plus the duration passed
as the valid_for parameter.
invalid_before: Option<UnixTimeStamp>The “Not Before” (nbf) claim - identifies the time before which the JWT must not be accepted.
This claim specifies the time before which the JWT must not be accepted for processing. It is represented as the number of seconds from 1970-01-01T00:00:00Z UTC (the UNIX epoch).
This field is automatically set when using Claims::create() or
Claims::with_custom_claims() to the current time, meaning the token is valid immediately.
It can be modified using the invalid_before() method.
issuer: Option<String>The “Issuer” (iss) claim - identifies the principal that issued the JWT.
This claim is a case-sensitive string and is typically a URI or an identifier for the issuing system. It can be used to validate tokens from specific trusted issuers.
This field is optional and can be set using the with_issuer() method.
subject: Option<String>The “Subject” (sub) claim - identifies the principal that is the subject of the JWT.
This claim is a case-sensitive string and typically contains an identifier for the user or entity on behalf of which the token was issued.
This field is optional and can be set using the with_subject() method.
audiences: Option<Audiences>The “Audience” (aud) claim - identifies the recipients that the JWT is intended for.
This claim can be either a string value or an array of strings, each of which typically identifies an intended recipient. Recipients must verify that they are among the intended audience values.
This field is optional and can be set using the with_audience() or with_audiences() methods.
jwt_id: Option<String>The “JWT ID” (jti) claim - provides a unique identifier for the JWT.
This claim creates a unique identifier for the token, which can be used to prevent the JWT from being replayed (i.e., using the same token multiple times).
While traditionally used for preventing replay attacks by storing all issued IDs, this is challenging to scale. A more practical approach is to use timestamps.
This field supports binary data through the custom Debug implementation that will display non-UTF8 data as hex-encoded strings.
This field is optional and can be set using the with_jwt_id() method.
nonce: Option<String>The “Nonce” claim - provides a random value to prevent replay attacks.
A nonce is a random value generated for use exactly once, which can be used to prevent replay attacks. When a new JWT is issued, the nonce can be stored temporarily and then checked when validating subsequent tokens.
This field supports binary data through the custom Debug implementation that will display non-UTF8 data as hex-encoded strings.
This field is optional and can be set using the with_nonce() or create_nonce() methods.
custom: CustomClaimsCustom application-defined claims.
This field allows for including custom, application-specific claims in the JWT.
It must be a type that implements Serialize and Deserialize.
Use NoCustomClaims if you don’t need any custom claims, or your own type
to include custom data.
Implementations§
Source§impl<CustomClaims> JWTClaims<CustomClaims>
impl<CustomClaims> JWTClaims<CustomClaims>
Sourcepub fn new() -> Selfwhere
CustomClaims: Default,
pub fn new() -> Selfwhere
CustomClaims: Default,
Create a new empty JWTClaims instance with default values
Sourcepub fn invalid_before(self, unix_timestamp: UnixTimeStamp) -> Self
pub fn invalid_before(self, unix_timestamp: UnixTimeStamp) -> Self
Sets the token as not being valid until the specified timestamp.
This sets the nbf (Not Before) claim, which specifies the time before which the token
must not be accepted for processing.
§Arguments
unix_timestamp- The UNIX timestamp (in seconds) before which the token should be rejected
§Returns
- The modified claims object for method chaining
§Example
use jwt_simple::prelude::*;
// Token will not be valid until 1 hour from now
let future_time = Clock::now_since_epoch() + Duration::from_hours(1);
let claims = Claims::create(Duration::from_hours(2))
.invalid_before(future_time);Sourcepub fn with_issuer(self, issuer: impl ToString) -> Self
pub fn with_issuer(self, issuer: impl ToString) -> Self
Sets the issuer claim (iss) for the token.
The issuer claim identifies the principal that issued the JWT. This can be used during token verification to ensure the token comes from a trusted issuer.
§Arguments
issuer- Any type that can be converted to a string, identifying the issuer
§Returns
- The modified claims object for method chaining
§Example
use jwt_simple::prelude::*;
let claims = Claims::create(Duration::from_hours(2))
.with_issuer("auth.example.com");Sourcepub fn with_subject(self, subject: impl ToString) -> Self
pub fn with_subject(self, subject: impl ToString) -> Self
Sets the subject claim (sub) for the token.
The subject claim identifies the principal that is the subject of the JWT. This is typically the user ID or another identifier for the token’s subject.
§Arguments
subject- Any type that can be converted to a string, identifying the subject
§Returns
- The modified claims object for method chaining
§Example
use jwt_simple::prelude::*;
let claims = Claims::create(Duration::from_hours(2))
.with_subject("user123@example.com");Sourcepub fn with_audiences(self, audiences: HashSet<impl ToString>) -> Self
pub fn with_audiences(self, audiences: HashSet<impl ToString>) -> Self
Sets multiple audience values (aud) for the token as a set.
The audience claim identifies the recipients that the JWT is intended for. This method allows specifying multiple audience values as a set.
§Arguments
audiences- A HashSet of audience values that can be converted to strings
§Returns
- The modified claims object for method chaining
§Example
use jwt_simple::prelude::*;
use std::collections::HashSet;
let mut audiences = HashSet::new();
audiences.insert("https://api.example.com");
audiences.insert("https://admin.example.com");
let claims = Claims::create(Duration::from_hours(2))
.with_audiences(audiences);Sourcepub fn with_audience(self, audience: impl ToString) -> Self
pub fn with_audience(self, audience: impl ToString) -> Self
Sets a single audience value (aud) for the token as a string.
The audience claim identifies the recipient that the JWT is intended for. This method is convenient when you only need to specify a single audience.
§Arguments
audience- Any type that can be converted to a string, identifying the audience
§Returns
- The modified claims object for method chaining
§Example
use jwt_simple::prelude::*;
let claims = Claims::create(Duration::from_hours(2))
.with_audience("https://api.example.com");Sourcepub fn with_jwt_id(self, jwt_id: impl ToString) -> Self
pub fn with_jwt_id(self, jwt_id: impl ToString) -> Self
Sets the JWT ID claim (jti) for the token.
The JWT ID claim provides a unique identifier for the JWT, which can be used to prevent the token from being replayed. This is useful when a one-time token is needed.
§Arguments
jwt_id- Any type that can be converted to a string, providing a unique ID
§Returns
- The modified claims object for method chaining
§Example
use jwt_simple::prelude::*;
let claims = Claims::create(Duration::from_hours(2))
.with_jwt_id("token-123456");Sourcepub fn with_nonce(self, nonce: impl ToString) -> Self
pub fn with_nonce(self, nonce: impl ToString) -> Self
Sets the nonce claim for the token.
A nonce is a random value that can be used to prevent replay attacks. When a new JWT is created, a nonce can be included and stored. When a JWT is received for verification, the previously stored nonce can be validated.
§Arguments
nonce- Any type that can be converted to a string, representing the nonce
§Returns
- The modified claims object for method chaining
§Example
use jwt_simple::prelude::*;
let claims = Claims::create(Duration::from_hours(2))
.with_nonce("random-nonce-value");Sourcepub fn create_nonce(&mut self) -> String
pub fn create_nonce(&mut self) -> String
Creates a cryptographically secure random nonce, attaches it to the claims, and returns it.
This method generates a 24-byte random nonce, encodes it using Base64UrlSafeNoPadding, attaches it to the claims, and returns the generated nonce. This is useful for creating tokens with built-in protection against replay attacks.
§Returns
- A string containing the Base64UrlSafeNoPadding-encoded nonce
§Example
use jwt_simple::prelude::*;
let mut claims = Claims::create(Duration::from_hours(2));
let nonce = claims.create_nonce();
// Store nonce for later verificationTrait Implementations§
Source§impl<CustomClaims: Debug> Debug for JWTClaims<CustomClaims>
Custom Debug implementation for JWTClaims to handle binary data fields.
impl<CustomClaims: Debug> Debug for JWTClaims<CustomClaims>
Custom Debug implementation for JWTClaims to handle binary data fields.
This implementation ensures that the jwt_id and nonce fields are displayed correctly,
even if they contain non-UTF8 data:
- For valid UTF-8 strings, displays them normally as strings
- For strings containing invalid UTF-8 sequences, displays them as hex-encoded values
This is necessary because JWT tokens can contain binary data in these fields when used with CBOR Web Tokens (CWT) or when binary data is base64-encoded into JWT claims.