Skip to main content

JWTClaims

Struct JWTClaims 

Source
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 NoCustomClaims if you only need the standard JWT claims
  • Use your own type that implements Serialize and Deserialize for custom claims

§Standard Claims

  • iss (Issuer): Identifies the principal that issued the JWT
  • sub (Subject): Identifies the principal that is the subject of the JWT
  • aud (Audience): Identifies the recipients the JWT is intended for
  • exp (Expiration Time): Identifies the time after which the JWT expires
  • nbf (Not Before): Identifies the time before which the JWT must not be accepted
  • iat (Issued At): Identifies the time at which the JWT was issued
  • jti (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 token
  • nonce: 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: CustomClaims

Custom 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>

Source

pub fn new() -> Self
where CustomClaims: Default,

Create a new empty JWTClaims instance with default values

Source

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);
Source

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");
Source

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");
Source

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);
Source

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");
Source

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");
Source

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");
Source

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 verification

Trait Implementations§

Source§

impl<CustomClaims: Clone> Clone for JWTClaims<CustomClaims>

Source§

fn clone(&self) -> JWTClaims<CustomClaims>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

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.

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for JWTClaims<NoCustomClaims>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de, CustomClaims> Deserialize<'de> for JWTClaims<CustomClaims>
where CustomClaims: Deserialize<'de>,

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<CustomClaims> Serialize for JWTClaims<CustomClaims>
where CustomClaims: Serialize,

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl<CustomClaims> Freeze for JWTClaims<CustomClaims>
where CustomClaims: Freeze,

§

impl<CustomClaims> RefUnwindSafe for JWTClaims<CustomClaims>
where CustomClaims: RefUnwindSafe,

§

impl<CustomClaims> Send for JWTClaims<CustomClaims>
where CustomClaims: Send,

§

impl<CustomClaims> Sync for JWTClaims<CustomClaims>
where CustomClaims: Sync,

§

impl<CustomClaims> Unpin for JWTClaims<CustomClaims>
where CustomClaims: Unpin,

§

impl<CustomClaims> UnsafeUnpin for JWTClaims<CustomClaims>
where CustomClaims: UnsafeUnpin,

§

impl<CustomClaims> UnwindSafe for JWTClaims<CustomClaims>
where CustomClaims: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,