Skip to main content

TokenManager

Struct TokenManager 

Source
#[non_exhaustive]
pub struct TokenManager { /* private fields */ }

Implementations§

Source§

impl TokenManager

Source

pub fn issue_sd_jwt( &self, sub: String, expires_in_secs: u64, aud: Option<String>, scope: Option<String>, disclosable_claims: Vec<DisclosableClaim>, extra: HashMap<String, Value>, ) -> Result<IssuedSdJwt, AuthError>

Issues an SD-JWT: a JWT whose payload carries _sd[] digests (and _sd_alg) for each of disclosable_claims, plus the matching Disclosure strings, serialized to SD-JWT compact form.

Works with whichever signing algorithm this TokenManager was constructed with — HS256 (TokenManager::new), RS256 (TokenManager::new_asymmetric), or Ed25519 (TokenManager::new_ed25519) — since the SD-JWT mechanism only concerns the payload (which claims are digested vs. plain), not how the JWT itself gets signed.

sub/expires_in_secs/aud/scope populate the same standard claims as TokenManager::issue_client_token_with_extra; extra is stamped the same way (including the extra["jti"] override — see [super::take_jti]). If disclosable_claims is empty, the result is a plain JWT: no _sd/_sd_alg claims are added, and compact == jwt with no trailing ~.

Reusing a claim name across disclosable_claims, or clashing with a key already in extra, is not rejected at issuance — each becomes its own Disclosure/digest, and a verifier will happily accept whichever ones it’s shown. Callers that need “exactly one value per name” are responsible for enforcing that themselves; nothing about the wire format requires it.

§Examples
let manager = TokenManager::new(b"example-secret", Some("issuer".to_string()));
let issued = manager.issue_sd_jwt(
    "user-1".to_string(),
    3600,
    None,
    None,
    vec![DisclosableClaim::new("email", "user@example.com")],
    HashMap::new(),
)?;
assert_eq!(issued.disclosures.len(), 1);
assert!(issued.compact.starts_with(&issued.jwt));
Source

pub fn validate_sd_jwt( &self, presented: &str, expected_aud: Option<&str>, ) -> Result<VerifiedSdJwt, AuthError>

Verifies a presented SD-JWT compact form (<jwt>~<d1>~...~, or a plain JWT with no ~ segments): validates the underlying JWT exactly as TokenManager::validate_token does (signature, issuer, audience, expiry), then checks every presented Disclosure against the validated _sd[]/_sd_alg, per the module-level security rules.

Rejects the whole presentation — not just the offending claim — if any Disclosure fails: digest not found in _sd[], a duplicate digest in _sd[], an unrecognized (present-and-different) _sd_alg, or a disclosed claim name that shadows a registered or already-present claim. See the module docs for why each of these has to fail closed rather than degrading gracefully.

§Examples
let manager = TokenManager::new(b"example-secret", Some("issuer".to_string()));
let issued = manager.issue_sd_jwt(
    "user-1".to_string(),
    3600,
    None,
    None,
    vec![DisclosableClaim::new("email", "user@example.com")],
    HashMap::new(),
)?;

// A holder can present the full compact form...
let verified = manager.validate_sd_jwt(&issued.compact, None)?;
assert_eq!(
    verified.disclosed_claims.get("email"),
    Some(&serde_json::Value::String("user@example.com".to_string()))
);

// ...or withhold the Disclosure entirely and present the bare JWT.
let bare = manager.validate_sd_jwt(&issued.jwt, None)?;
assert!(bare.disclosed_claims.is_empty());
Source§

impl TokenManager

Source

pub fn new(secret: &[u8], issuer: Option<String>) -> Self

Creates a TokenManager for symmetric signing (HS256).

Source

pub fn new_asymmetric( private_key_pem: &[u8], issuer: Option<String>, kid: Option<String>, ) -> Result<Self, AuthError>

Creates a TokenManager for asymmetric signing (RS256). private_key_pem must be a valid RSA private key in PEM format. OP/external verification should use this path; internal resource servers can continue to use new (HS256).

Source

pub fn new_ed25519( private_key_pem: &[u8], issuer: Option<String>, kid: Option<String>, ) -> Result<Self, AuthError>

Creates a TokenManager for asymmetric signing with Ed25519 (EdDSA). private_key_pem must be a valid Ed25519 private key in PKCS#8 PEM format (-----BEGIN PRIVATE KEY-----), e.g. as produced by openssl genpkey -algorithm ed25519.

Mirrors new_asymmetric (RS256): OP/external verification should use this path when downstream resource servers require EdDSA-signed tokens; internal resource servers can continue to use new (HS256). The published JWK (public_jwk) is the OKP shape from RFC 8037, so pair this with #188 (Jwk’s OKP support) to publish a verifiable /jwks.json for the resulting deployment.

Source

pub fn public_jwk(&self) -> Option<Jwk>

Source

pub fn with_issuer(self, issuer: String) -> Self

Source

pub fn issue_user_token( &self, identity: Identity, expires_in_secs: u64, scope: Option<String>, aud: Option<String>, ) -> Result<String, AuthError>

Issues a token for a user identity.

Source

pub fn issue_user_token_with_extra( &self, identity: Identity, expires_in_secs: u64, scope: Option<String>, aud: Option<String>, extra: HashMap<String, Value>, ) -> Result<String, AuthError>

Issues a token for a user identity, stamping the given extra claims onto the token in addition to the standard/core claims.

This lets a host application (e.g. a resource server built on top of this engine) attach domain-specific claims — such as api_key_id, project_id, or roles — so downstream consumers (an API gateway or authorization proxy) can read them directly off the token without a database round-trip. Keys in extra take precedence over any same-named field set elsewhere in extra by this method; they cannot override the top-level standard claims (sub, aud, exp, etc.) since those are not part of the flattened map, with one exception: jti is a reserved key. If extra["jti"] is a JSON string, it is removed from extra and used verbatim as the token’s jti claim instead of a generated UUIDv4 — see [take_jti] for why this has to happen this way rather than leaving the key in extra. nbf (not-before, set to issuance time) and identity are unconditional parts of this token’s contract and have no opt-out.

Source

pub fn issue_id_token( &self, identity: Identity, client_id: &str, nonce: Option<String>, expires_in_secs: u64, ) -> Result<String, AuthError>

Issues an OIDC-conformant ID token.

Source

pub fn issue_id_token_with_extra( &self, identity: Identity, client_id: &str, nonce: Option<String>, expires_in_secs: u64, extra: HashMap<String, Value>, ) -> Result<String, AuthError>

Issues an OIDC-conformant ID token, stamping the given extra claims onto the token in addition to the standard/core claims.

nonce is a reserved claim key: extra is merged into the token first, then the explicit nonce parameter is applied on top. So if nonce is Some(_), it always wins over any "nonce" entry passed in extra. If nonce is None, an extra["nonce"] value (if any) is left as-is. This preserves OIDC nonce semantics — it reflects what the client sent in the authorization request — and keeps it from being accidentally clobbered by unrelated custom claims.

jti is likewise reserved: see Self::issue_user_token_with_extra for how extra["jti"] overrides the generated one. nbf and identity are unconditional on this path too, with no opt-out.

Source

pub fn issue_client_token( &self, client_id: &str, expires_in_secs: u64, scope: Option<String>, aud: Option<String>, ) -> Result<String, AuthError>

Issues a machine-to-machine (M2M) token for a client.

Source

pub fn issue_client_token_with_extra( &self, client_id: &str, expires_in_secs: u64, scope: Option<String>, aud: Option<String>, extra: HashMap<String, Value>, ) -> Result<String, AuthError>

Issues a machine-to-machine (M2M) token for a client, stamping the given extra claims onto the token in addition to the standard/core claims. See Self::issue_user_token_with_extra for the rationale, including the extra["jti"] override.

Source

pub fn issue_custom_token( &self, sub: String, expires_in_secs: u64, typ: &str, extra: HashMap<String, Value>, ) -> Result<String, AuthError>

Issues a token with an explicit typ header and no aud, for callers minting something that is not a standard OIDC ID/access/user token and needs its own wire-format typ so verifiers can tell it apart from those (e.g. authkestra-op’s device/service attestations, whose contract requires typ: "webank-attest+jws" rather than the default "JWT"). Additive alongside the issue_*_token* family above; those are unchanged. extra["jti"] is honored the same way as Self::issue_user_token_with_extra.

Source

pub fn validate_token( &self, token: &str, expected_aud: Option<&str>, ) -> Result<Claims, AuthError>

Trait Implementations§

Source§

impl Clone for TokenManager

Source§

fn clone(&self) -> TokenManager

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

Auto Trait Implementations§

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

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

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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

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

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 = !

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.
Source§

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

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more