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 systemsscopes: 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 tracingip_address: Client IP address for geolocation and fraud detectionauthenticated_at: When the JWT was issuedexpires_at: When the JWT expiresissuer: Token issuer for multi-issuer systemsaudience: Token audience for validation
Fields§
§user_id: StringUser 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:userwrite:postread:User.emailadmin:*
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: StringRequest 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
impl SecurityContext
Sourcepub fn from_user(user: AuthenticatedUser, request_id: String) -> Self
pub fn from_user(user: AuthenticatedUser, request_id: String) -> Self
Sourcepub fn get_attribute(&self, key: &str) -> Option<&Value>
pub fn get_attribute(&self, key: &str) -> Option<&Value>
Sourcepub fn is_expired(&self) -> bool
pub fn is_expired(&self) -> bool
Sourcepub fn is_multi_tenant(&self) -> bool
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.
Sourcepub fn with_role(self, role: String) -> Self
pub fn with_role(self, role: String) -> Self
Set or override a role (for testing or runtime role modification).
Sourcepub fn with_scopes(self, scopes: Vec<String>) -> Self
pub fn with_scopes(self, scopes: Vec<String>) -> Self
Set or override scopes (for testing or runtime permission modification).
Sourcepub fn with_tenant(self, tenant_id: String) -> Self
pub fn with_tenant(self, tenant_id: String) -> Self
Set tenant ID (for multi-tenancy).
Sourcepub fn with_attribute(self, key: String, value: Value) -> Self
pub fn with_attribute(self, key: String, value: Value) -> Self
Set a custom attribute (for testing or runtime attribute addition).
Sourcepub fn can_access_scope(
&self,
security_config: &SecurityConfig,
required_scope: &str,
) -> bool
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 definitionsrequired_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
impl Clone for SecurityContext
Source§fn clone(&self) -> SecurityContext
fn clone(&self) -> SecurityContext
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for SecurityContext
impl Debug for SecurityContext
Source§impl<'de> Deserialize<'de> for SecurityContext
impl<'de> Deserialize<'de> for SecurityContext
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Source§impl Display for SecurityContext
impl Display for SecurityContext
Auto Trait Implementations§
impl Freeze for SecurityContext
impl RefUnwindSafe for SecurityContext
impl Send for SecurityContext
impl Sync for SecurityContext
impl Unpin for SecurityContext
impl UnsafeUnpin for SecurityContext
impl UnwindSafe for SecurityContext
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
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
Source§impl<T> ToStringFallible for Twhere
T: Display,
impl<T> ToStringFallible for Twhere
T: Display,
Source§fn try_to_string(&self) -> Result<String, TryReserveError>
fn try_to_string(&self) -> Result<String, TryReserveError>
ToString::to_string, but without panic on OOM.