Skip to main content

AuthSession

Struct AuthSession 

Source
pub struct AuthSession {
    pub id_token: String,
    pub access_token: String,
    pub token_type: String,
    pub refresh_token: String,
    pub scope: String,
    pub expires: DateTime<Local>,
}
Expand description

Authenticated user session containing OAuth2/OIDC tokens.

This struct holds all the token information obtained from the OAuth2 provider after successful authentication. It is stored in the cache and automatically refreshed when tokens expire.

§Fields

  • id_token - OpenID Connect ID token (JWT) containing user identity claims
  • access_token - OAuth2 access token for API authorization
  • token_type - Token type, typically “Bearer”
  • refresh_token - Refresh token for obtaining new access tokens
  • scope - Space-separated list of granted scopes
  • expires - Expiration timestamp for the access token

§Automatic Token Refresh

When used as an extractor in route handlers, this session is automatically refreshed if the access token has expired. The refresh process:

  1. Checks if expires is in the past
  2. Uses refresh_token to request a new access token
  3. Updates access_token, id_token, and expires with fresh values
  4. Persists the updated session to cache

§Usage as Extractor

use axum_oidc_client::auth_session::AuthSession;

async fn protected_route(session: AuthSession) -> String {
    // Session is automatically refreshed if expired
    format!(
        "Welcome! Your session:\n\
         Token Type: {}\n\
         Expires: {}\n\
         Scopes: {}",
        session.token_type,
        session.expires,
        session.scope
    )
}

§Examples

§Accessing Token Information

use axum_oidc_client::auth_session::AuthSession;

async fn show_session(session: AuthSession) -> String {
    format!("Access Token: {}", session.access_token)
}

§Making Authenticated API Calls

use axum_oidc_client::auth_session::AuthSession;
use reqwest::Client;

async fn call_api(session: AuthSession) -> Result<String, Box<dyn std::error::Error>> {
    let client = Client::new();
    let response = client
        .get("https://api.example.com/data")
        .bearer_auth(&session.access_token)
        .send()
        .await?;
    Ok(response.text().await?)
}

§Checking Expiration

use axum_oidc_client::auth_session::AuthSession;
use chrono::Local;

async fn check_session(session: AuthSession) -> String {
    let now = Local::now();
    let is_expired = session.expires <= now;

    // Note: When using the extractor, tokens are auto-refreshed
    // so is_expired will typically be false
    format!("Token expired: {}", is_expired)
}

Fields§

§id_token: String

OpenID Connect ID token (JWT) containing user identity information

§access_token: String

OAuth2 access token for authorizing API requests

§token_type: String

Token type, typically “Bearer”

§refresh_token: String

Refresh token for obtaining new access tokens when they expire

§scope: String

Space-separated list of OAuth2 scopes granted to this session

§expires: DateTime<Local>

Timestamp when the access token expires

Implementations§

Source§

impl AuthSession

Source

pub fn new(response: &AccessTokenResponse, conf: &OAuthConfiguration) -> Self

Trait Implementations§

Source§

impl Clone for AuthSession

Source§

fn clone(&self) -> AuthSession

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 AuthSession

Source§

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

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

impl<'de> Deserialize<'de> for AuthSession

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<S> FromRequestParts<S> for AuthSession
where S: Send + Sync,

Source§

type Rejection = Response<Body>

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

fn from_request_parts<'a>( parts: &'a mut Parts, _state: &S, ) -> BoxFuture<'a, Result<Self, Self::Rejection>>

Perform the extraction.
Source§

impl PartialEq for AuthSession

Source§

fn eq(&self, other: &AuthSession) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for AuthSession

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

impl StructuralPartialEq for AuthSession

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<S, T> FromRequest<S, ViaParts> for T
where S: Send + Sync, T: FromRequestParts<S>,

Source§

type Rejection = <T as FromRequestParts<S>>::Rejection

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

fn from_request( req: Request<Body>, state: &S, ) -> impl Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>>

Perform the extraction.
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
Source§

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

Source§

impl<T> ErasedDestructor for T
where T: 'static,