Skip to main content

SecurityContext

Struct SecurityContext 

Source
pub struct SecurityContext {
    pub user_id: String,
    pub roles: Vec<String>,
    pub tenant_id: Option<String>,
    pub scopes: Vec<String>,
    pub attributes: HashMap<String, Value>,
    pub request_id: String,
    pub ip_address: Option<String>,
    pub authenticated_at: DateTime<Utc>,
    pub expires_at: DateTime<Utc>,
    pub issuer: Option<String>,
    pub audience: Option<String>,
}
Expand description

Security context for authorization evaluation.

Carries information about the authenticated user and their permissions throughout the request lifecycle.

§Fields

  • user_id: Unique identifier for the authenticated user (from JWT ‘sub’ claim)
  • roles: User’s roles (e.g., [“admin”, “moderator”], from JWT ‘roles’ claim)
  • tenant_id: Organization/tenant identifier for multi-tenant systems
  • scopes: OAuth/permission scopes (e.g., [“read:user”, “write:post”])
  • attributes: Custom claims from JWT (e.g., department, region, tier)
  • request_id: Correlation ID for audit logging and tracing
  • ip_address: Client IP address for geolocation and fraud detection
  • authenticated_at: When the JWT was issued
  • expires_at: When the JWT expires
  • issuer: Token issuer for multi-issuer systems
  • audience: Token audience for validation

Fields§

§user_id: String

User ID (from JWT ‘sub’ claim)

§roles: Vec<String>

User’s roles (e.g., [“admin”, “moderator”])

Extracted from JWT ‘roles’ claim or derived from other claims. Used for role-based access control (RBAC) decisions.

§tenant_id: Option<String>

Tenant/organization ID (for multi-tenancy)

When present, RLS policies can enforce tenant isolation. Extracted from JWT ‘tenant_id’ or X-Tenant-Id header.

§scopes: Vec<String>

OAuth/permission scopes

Format: {action}:{resource} or {action}:{type}.{field} Examples:

  • read:user
  • write:post
  • read:User.email
  • admin:*

Extracted from JWT ‘scope’ claim.

§attributes: HashMap<String, Value>

Custom attributes from JWT claims

Arbitrary key-value pairs from JWT payload. Examples: “department”, “region”, “tier”, “country”

Used by custom RLS policies that need domain-specific attributes.

§request_id: String

Request correlation ID for audit trails

Extracted from X-Request-Id header or generated. Used for tracing and audit logging across services.

§ip_address: Option<String>

Client IP address

Extracted from X-Forwarded-For or connection socket. Used for geolocation and fraud detection in RLS policies.

§authenticated_at: DateTime<Utc>

When the JWT was issued

§expires_at: DateTime<Utc>

When the JWT expires

§issuer: Option<String>

Token issuer (for multi-issuer systems)

§audience: Option<String>

Token audience (for audience validation)

Implementations§

Source§

impl SecurityContext

Source

pub fn from_user(user: AuthenticatedUser, request_id: String) -> Self

Create a security context from an authenticated user and request metadata.

§Arguments
  • user - Authenticated user from JWT validation
  • request_id - Correlation ID for this request
§Example
let context = SecurityContext::from_user(authenticated_user, "req-123")?;
Source

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

Check if the user has a specific role.

§Arguments
  • role - Role name to check (e.g., “admin”, “moderator”)
§Returns

true if the user has the specified role, false otherwise.

Source

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

Check if the user has a specific scope.

Supports wildcards: admin:* matches any admin scope.

§Arguments
  • scope - Scope to check (e.g., “read:user”, “write:post”)
§Returns

true if the user has the specified scope, false otherwise.

Source

pub fn get_attribute(&self, key: &str) -> Option<&Value>

Get a custom attribute from the JWT claims.

§Arguments
  • key - Attribute name
§Returns

The attribute value if present, None otherwise.

Source

pub fn is_expired(&self) -> bool

Check if the token has expired.

§Returns

true if the JWT has expired, false otherwise.

Source

pub fn ttl_secs(&self) -> i64

Get time until expiry in seconds.

§Returns

Seconds until JWT expiry, negative if already expired.

Source

pub fn is_admin(&self) -> bool

Check if the user is an admin.

§Returns

true if the user has the “admin” role, false otherwise.

Source

pub fn is_multi_tenant(&self) -> bool

Check if the context has a tenant ID (multi-tenancy enabled).

§Returns

true if tenant_id is present, false otherwise.

Source

pub fn with_role(self, role: String) -> Self

Set or override a role (for testing or runtime role modification).

Source

pub fn with_scopes(self, scopes: Vec<String>) -> Self

Set or override scopes (for testing or runtime permission modification).

Source

pub fn with_tenant(self, tenant_id: String) -> Self

Set tenant ID (for multi-tenancy).

Source

pub fn with_attribute(self, key: String, value: Value) -> Self

Set a custom attribute (for testing or runtime attribute addition).

Source

pub fn can_access_scope( &self, security_config: &SecurityConfig, required_scope: &str, ) -> bool

Check if user can access a field based on role definitions.

Takes a required scope and checks if any of the user’s roles grant that scope.

§Arguments
  • security_config - Security config from compiled schema with role definitions
  • required_scope - Scope required to access the field (e.g., “read:User.email”)
§Returns

true if user’s roles grant the required scope, false otherwise.

§Example
let config = SecurityConfig::new();
let can_access = context.can_access_scope(&config, "read:User.email")?;

Trait Implementations§

Source§

impl Clone for SecurityContext

Source§

fn clone(&self) -> SecurityContext

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 SecurityContext

Source§

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

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

impl<'de> Deserialize<'de> for SecurityContext

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 Display for SecurityContext

Source§

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

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

impl Serialize for SecurityContext

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> 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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T> ToStringFallible for T
where T: Display,

Source§

fn try_to_string(&self) -> Result<String, TryReserveError>

ToString::to_string, but without panic on OOM.

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