pub struct Cat { /* private fields */ }Expand description
Common Access Token (CAT) validator and generator.
This is the main struct for working with CAT tokens. It provides methods for:
- Generating tokens from claims
- Validating tokens and extracting claims
- Converting between JSON and CAT claims
§Examples
use common_access_token::{Cat, CatOptions, CatGenerateOptions, CatValidationOptions, CatValidationType, Claims};
use std::collections::HashMap;
// Create a CAT instance
let key = hex::decode("403697de87af64611c1d32a05dab0fe1fcb715a86ab435f1ec99192d79569388").unwrap();
let cat = Cat::new(CatOptions {
keys: HashMap::from([("key-1".to_string(), key)]),
expect_cwt_tag: true,
});
// Create and generate a token
let mut claims = Claims::new();
claims.set_issuer("example");
let token = cat.generate(claims, &CatGenerateOptions {
validation_type: CatValidationType::Mac,
alg: "HS256".to_string(),
kid: "key-1".to_string(),
generate_cwt_id: true,
}).unwrap();
// Validate the token
let validation_options = CatValidationOptions {
issuer: "example".to_string(),
audience: None,
};
let validated_claims = cat.validate(&token, CatValidationType::Mac, &validation_options).unwrap();Implementations§
Source§impl Cat
impl Cat
Sourcepub fn new(opts: CatOptions) -> Self
pub fn new(opts: CatOptions) -> Self
Creates a new CAT instance with the specified options.
§Arguments
opts- Configuration options including cryptographic keys and format settings
§Examples
use common_access_token::{Cat, CatOptions};
use std::collections::HashMap;
let key = hex::decode("403697de87af64611c1d32a05dab0fe1fcb715a86ab435f1ec99192d79569388").unwrap();
let cat = Cat::new(CatOptions {
keys: HashMap::from([("key-1".to_string(), key)]),
expect_cwt_tag: true,
});Sourcepub fn validate(
&self,
token: &str,
validation_type: CatValidationType,
opts: &CatValidationOptions,
) -> Result<Claims, Error>
pub fn validate( &self, token: &str, validation_type: CatValidationType, opts: &CatValidationOptions, ) -> Result<Claims, Error>
Validates a CAT token and returns the claims if valid.
This method performs several validation steps:
- Decodes the token from base64
- Verifies the cryptographic signature/MAC
- Validates the claims (issuer, expiration, audience)
§Arguments
token- The CAT token as a base64url-encoded stringvalidation_type- The type of validation to perform (Mac, Sign, or None)opts- Options controlling validation behavior
§Returns
Ok(Claims)- The validated claims from the tokenErr(Error)- An error indicating why validation failed
§Examples
// Validate a token
let token = "..."; // Base64url-encoded token
let validation_options = CatValidationOptions {
issuer: "trusted-issuer".to_string(),
audience: Some(vec!["my-app".to_string()]),
};
match cat.validate(token, CatValidationType::Mac, &validation_options) {
Ok(claims) => {
println!("Token is valid!");
println!("Subject: {:?}", claims.get_subject());
},
Err(err) => {
println!("Token validation failed: {}", err);
}
}Sourcepub fn generate(
&self,
claims: Claims,
opts: &CatGenerateOptions,
) -> Result<String, Error>
pub fn generate( &self, claims: Claims, opts: &CatGenerateOptions, ) -> Result<String, Error>
Generates a CAT token from the provided claims.
This method creates a token by:
- Optionally generating a CWT ID if requested
- Serializing the claims to CBOR
- Creating a cryptographic signature/MAC
- Encoding the result as a base64url string
§Arguments
claims- The claims to include in the tokenopts- Options controlling token generation
§Returns
Ok(String)- The generated token as a base64url-encoded stringErr(Error)- An error indicating why token generation failed
§Examples
// Create claims
let mut claims = Claims::new();
claims.set_issuer("my-service");
claims.set_subject("user-123");
claims.set_audience("client-app");
// Set expiration time
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
claims.set_expiration(now + 3600); // 1 hour from now
// Generate the token
let token = cat.generate(claims, &CatGenerateOptions {
validation_type: CatValidationType::Mac,
alg: "HS256".to_string(),
kid: "key-1".to_string(),
generate_cwt_id: true,
}).unwrap();
println!("Generated token: {}", token);Sourcepub fn generate_from_json(
&self,
json_claims: Value,
opts: &CatGenerateOptions,
) -> Result<String, Error>
pub fn generate_from_json( &self, json_claims: Value, opts: &CatGenerateOptions, ) -> Result<String, Error>
Generates a CAT token from a JSON object containing claims.
This is a convenience method that converts JSON claims to a Claims object
and then generates a token. It’s useful when working with JSON data from
external sources.
§Arguments
json_claims- JSON object containing claims (e.g.,{"iss": "issuer", "sub": "subject"})opts- Options controlling token generation
§Returns
Ok(String)- The generated token as a base64url-encoded stringErr(Error)- An error indicating why token generation failed
§Examples
// Create claims as JSON
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let json_claims = json!({
"iss": "my-service",
"sub": "user-123",
"aud": "client-app",
"exp": now + 3600, // 1 hour from now
"iat": now
});
// Generate the token
let token = cat.generate_from_json(json_claims, &CatGenerateOptions {
validation_type: CatValidationType::Mac,
alg: "HS256".to_string(),
kid: "key-1".to_string(),
generate_cwt_id: true,
}).unwrap();Sourcepub fn resign_token(
&self,
token: &str,
validation_opts: &CatValidationOptions,
new_expiration: i64,
generate_opts: &CatGenerateOptions,
) -> Result<String, Error>
pub fn resign_token( &self, token: &str, validation_opts: &CatValidationOptions, new_expiration: i64, generate_opts: &CatGenerateOptions, ) -> Result<String, Error>
Converts a JSON object to a Claims object.
This method maps standard JWT claim names to their CWT equivalents:
- “iss” -> issuer
- “sub” -> subject
- “aud” -> audience
- “exp” -> expiration
- “nbf” -> not before
- “iat” -> issued at
- “cti” -> CWT ID
§Arguments
json_claims- JSON object containing claimsopts- Generation options (used for CWT ID generation)
§Returns
Ok(Claims)- The converted claimsErr(Error)- An error if conversion fails Re-signs an existing token with a new expiration time.
This method extends the lifetime of an existing token by:
- Validating the existing token
- Extracting the claims
- Updating the expiration time
- Generating a new token with the updated claims
§Arguments
token- The existing token to re-signvalidation_opts- Options for validating the existing tokennew_expiration- The new expiration time (in seconds since UNIX epoch)generate_opts- Options for generating the new token
§Returns
Ok(String)- The newly generated token with extended lifetimeErr(Error)- An error if token validation or generation fails
§Examples
// Validation options for the existing token
let validation_options = CatValidationOptions {
issuer: "trusted-issuer".to_string(),
audience: None,
};
// Calculate new expiration time (e.g., 1 hour from now)
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let new_expiration = now + 3600;
// Generation options for the new token
let generate_options = CatGenerateOptions {
validation_type: CatValidationType::Mac,
alg: "HS256".to_string(),
kid: "key-1".to_string(),
generate_cwt_id: true, // Generate a new CWT ID
};
// Re-sign the token with the new expiration
let new_token = cat.resign_token(
&existing_token,
&validation_options,
new_expiration,
&generate_options
).unwrap();Trait Implementations§
Auto Trait Implementations§
impl Freeze for Cat
impl RefUnwindSafe for Cat
impl Send for Cat
impl Sync for Cat
impl Unpin for Cat
impl UnwindSafe for Cat
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more