AuthContext

Struct AuthContext 

Source
pub struct AuthContext {
Show 18 fields pub sub: String, pub iss: Option<String>, pub aud: Option<String>, pub exp: Option<u64>, pub iat: Option<u64>, pub nbf: Option<u64>, pub jti: Option<String>, pub user: UserInfo, pub roles: Vec<String>, pub permissions: Vec<String>, pub scopes: Vec<String>, pub request_id: Option<String>, pub authenticated_at: SystemTime, pub expires_at: Option<SystemTime>, pub token: Option<TokenInfo>, pub provider: String, pub dpop_jkt: Option<String>, pub metadata: HashMap<String, Value>,
}
Expand description

Unified authentication context containing user identity, claims, and session metadata.

This type serves as both:

  • The internal authentication representation
  • The JWT claims structure (via to_jwt_claims / from_jwt_claims)

§Standard JWT Claims (RFC 7519)

  • sub: Subject (user ID)
  • iss: Issuer (who issued the token)
  • aud: Audience (who the token is for)
  • exp: Expiration time (Unix timestamp)
  • iat: Issued at (Unix timestamp)
  • nbf: Not before (Unix timestamp)
  • jti: JWT ID (unique identifier)

§Extended Claims

  • user: Full user information
  • roles: RBAC roles
  • permissions: Fine-grained permissions
  • scopes: OAuth scopes
  • request_id: Request identifier for replay protection (NOT session-based)
  • provider: Auth provider identifier
  • metadata: Custom claims

§Example

use turbomcp_auth::context::{AuthContext, AuthContextBuilder};

let ctx = AuthContext::builder()
    .subject("user123")
    .user(user_info)
    .roles(vec!["admin".into(), "user".into()])
    .permissions(vec!["read:posts".into(), "write:posts".into()])
    .build();

// Check authorization
if ctx.has_role("admin") && ctx.has_permission("write:posts") {
    // Allow action
}

Fields§

§sub: String

Subject (typically user ID)

§iss: Option<String>

Issuer (who issued this token)

§aud: Option<String>

Audience (who this token is for)

§exp: Option<u64>

Expiration time (Unix timestamp)

§iat: Option<u64>

Issued at (Unix timestamp)

§nbf: Option<u64>

Not before (Unix timestamp)

§jti: Option<String>

JWT ID (unique identifier)

§user: UserInfo

Full user information

§roles: Vec<String>

RBAC roles (e.g., [“admin”, “user”])

§permissions: Vec<String>

Fine-grained permissions (e.g., [“read:posts”, “write:posts”])

§scopes: Vec<String>

OAuth scopes (e.g., [“openid”, “email”, “profile”])

§request_id: Option<String>

Request ID for nonce/replay protection (MCP compliant - NOT session-based)

Per MCP security requirements, servers MUST NOT use sessions for authentication. This field is for request-level binding (DPoP nonces, one-time tokens, etc.), not session management. Each request must include valid credentials.

§authenticated_at: SystemTime

When authentication occurred

§expires_at: Option<SystemTime>

When this context expires (may differ from JWT exp)

§token: Option<TokenInfo>

Token information (access + refresh tokens)

§provider: String

Auth provider (e.g., “oauth2:google”, “api_key”, “jwt:internal”)

§dpop_jkt: Option<String>

DPoP JWK thumbprint for token binding

§metadata: HashMap<String, Value>

Custom metadata (tenant_id, org_id, etc.)

Implementations§

Source§

impl AuthContext

Source

pub fn builder() -> AuthContextBuilder

Create builder for constructing auth context

Source

pub fn to_jwt_claims(&self) -> Value

Convert to JWT claims (for signing)

Serializes the entire AuthContext into a JSON value suitable for JWT encoding. Standard JWT claims (sub, iss, aud, exp, iat, nbf, jti) are included at the top level.

§Example
let claims = auth_ctx.to_jwt_claims();
let token = jwt_encoder.encode(&claims)?;
Source

pub fn from_jwt_claims(claims: Value) -> Result<Self, AuthError>

Create from JWT claims (after validation)

Deserializes a validated JWT claims object into an AuthContext.

§Errors

Returns error if:

  • Required fields are missing (sub, user, provider)
  • Field types don’t match expected types
  • Invalid timestamps
Source

pub fn is_expired(&self) -> bool

Check if token is expired

Uses expires_at field if present, otherwise falls back to exp claim.

Source

pub fn validate(&self, config: &ValidationConfig) -> Result<(), AuthError>

Validate all fields (exp, nbf, aud, iss)

Performs comprehensive validation according to RFC 7519.

§Errors

Returns error if:

  • Token is expired (with leeway)
  • Token not yet valid (nbf with leeway)
  • Audience mismatch
  • Issuer mismatch
Source

pub fn has_role(&self, role: &str) -> bool

Check if user has specific role

Source

pub fn has_any_role(&self, roles: &[&str]) -> bool

Check if user has any of the roles

Source

pub fn has_all_roles(&self, roles: &[&str]) -> bool

Check if user has all of the roles

Source

pub fn has_permission(&self, perm: &str) -> bool

Check if user has specific permission

Source

pub fn has_any_permission(&self, perms: &[&str]) -> bool

Check if user has any of the permissions

Source

pub fn has_all_permissions(&self, perms: &[&str]) -> bool

Check if user has all of the permissions

Source

pub fn has_scope(&self, scope: &str) -> bool

Check if token has specific scope

Source

pub fn has_any_scope(&self, scopes: &[&str]) -> bool

Check if token has any of the scopes

Source

pub fn has_all_scopes(&self, scopes: &[&str]) -> bool

Check if token has all of the scopes

Source

pub fn get_metadata<T: DeserializeOwned>(&self, key: &str) -> Option<T>

Get custom metadata value

Deserializes a custom metadata field into the specified type.

§Example
if let Some(tenant_id) = auth_ctx.get_metadata::<String>("tenant_id") {
    println!("Tenant: {}", tenant_id);
}
Source

pub fn validate_dpop_proof(&self, proof: &DpopProof) -> Result<(), AuthError>

Validate DPoP proof (RFC 9449)

Verifies that the DPoP proof matches the bound JWK thumbprint.

Trait Implementations§

Source§

impl Clone for AuthContext

Source§

fn clone(&self) -> AuthContext

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for AuthContext

Source§

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

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

impl<'de> Deserialize<'de> for AuthContext

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 Serialize for AuthContext

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§

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

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: 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: 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> 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.
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
Source§

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