Skip to main content

JwtSessionService

Struct JwtSessionService 

Source
pub struct JwtSessionService { /* private fields */ }
Expand description

Stateful JWT session service.

Manages the full lifecycle of JWT-based sessions backed by a SQLite session table. Each session is represented as a database row — the jti claim in both the access and refresh tokens contains the hex-encoded session token, which is hashed before storage.

Cloning is cheap — all state is behind Arc.

§Session lifecycle

  1. authenticate — creates a new session row, issues an access + refresh token pair.
  2. rotate — validates the refresh token, rotates the stored token hash, issues a new pair.
  3. logout — validates the access token, destroys the session row.

§Wiring

let config = JwtSessionsConfig::new("my-super-secret-key-for-signing-tokens");
let svc = JwtSessionService::new(db, config)?;

// Authenticate a user (e.g. after password check)
let meta = SessionMeta::from_headers(ip, user_agent, accept_language, accept_encoding);
let pair = svc.authenticate("user_123", &meta).await?;

// Rotate (called from the refresh endpoint)
let new_pair = svc.rotate(&pair.refresh_token).await?;

// Logout (called from the logout endpoint)
svc.logout(&pair.access_token).await?;

Implementations§

Source§

impl JwtSessionService

Source

pub fn new(db: Database, config: JwtSessionsConfig) -> Result<Self>

Create a new JwtSessionService.

Validates that signing_secret is non-empty and builds the encoder, decoder, and session store. Returns an error immediately if the config is invalid — fail fast at startup.

§Errors

Returns Error::internal if signing_secret is empty.

Source

pub fn encoder(&self) -> &JwtEncoder

Returns a reference to the JWT encoder.

Source

pub fn decoder(&self) -> &JwtDecoder

Returns a reference to the JWT decoder.

Source

pub fn config(&self) -> &JwtSessionsConfig

Returns a reference to the service configuration.

Source

pub fn layer(&self) -> JwtLayer

Creates a JwtLayer backed by this service.

The returned layer performs stateful validation: after verifying the JWT signature and claims it hashes the jti, loads the session row, and inserts the transport-agnostic Session into request extensions. Returns 401 when the session row is absent.

§Example
let svc = JwtSessionService::new(db, config)?;
let app = Router::new()
    .route("/me", get(whoami).route_layer(svc.layer()));
Source

pub async fn authenticate( &self, user_id: &str, meta: &SessionMeta, ) -> Result<TokenPair>

Authenticate a user and issue a new TokenPair.

Creates a session row in the database. The access and refresh tokens both carry the session token hex as the jti claim. The access token audience is "access"; the refresh token audience is "refresh".

§Errors

Returns an error if the session row cannot be created or the tokens cannot be signed.

Source

pub async fn rotate(&self, refresh_token: &str) -> Result<TokenPair>

Rotate a refresh token, issuing a new TokenPair.

Validates the provided refresh_token (signature, expiry, audience), then rotates the stored session token hash and mints a fresh pair. The old refresh token is immediately invalidated — a second call with the same token returns auth:session_not_found.

§Errors
  • auth:aud_mismatch — the token has the wrong audience (e.g. an access token was passed).
  • auth:session_not_found — the session row does not exist or has expired.
  • JWT validation errors (jwt:*) — expired, tampered, etc.
Source

pub async fn logout(&self, access_token: &str) -> Result<()>

Revoke the session associated with an access token.

Validates the access_token (signature, expiry, audience), then destroys the session row. If the session is already gone (e.g. concurrent logout), the call is a no-op and succeeds.

§Errors
  • auth:aud_mismatch — a refresh token was passed instead of an access token.
  • JWT validation errors (jwt:*) — expired, tampered, etc.
Source

pub async fn list(&self, user_id: &str) -> Result<Vec<Session>>

List all active sessions for the given user.

§Errors

Returns an error if the database query fails.

Source

pub async fn revoke(&self, user_id: &str, id: &str) -> Result<()>

Revoke a specific session by its ULID identifier.

Looks up the session row by id, verifies that it belongs to user_id, and destroys it. Returns 404 auth:session_not_found if the session does not exist or belongs to a different user.

§Errors

Returns 404 auth:session_not_found on ownership mismatch, or an internal error if the database operation fails.

Source

pub async fn revoke_all(&self, user_id: &str) -> Result<()>

Revoke all sessions for the given user.

§Errors

Returns an error if the database delete fails.

Source

pub async fn revoke_all_except( &self, user_id: &str, keep_id: &str, ) -> Result<()>

Revoke all sessions for the given user except the session with keep_id.

Used to implement “log out other devices”.

§Errors

Returns an error if the database delete fails.

Source

pub async fn cleanup_expired(&self) -> Result<u64>

Delete all expired sessions from the database.

Returns the number of rows deleted. Schedule periodically (e.g. via a cron job) to keep the table small.

§Errors

Returns an error if the database delete fails.

Trait Implementations§

Source§

impl Clone for JwtSessionService

Source§

fn clone(&self) -> JwtSessionService

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

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> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
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, 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