Skip to main content

OAuthTokenProvider

Struct OAuthTokenProvider 

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

Manages OAuth access tokens, including caching and automatic refresh.

This provider implements thread-safe token management with automatic expiration handling. It uses a double-checked locking pattern to minimize lock contention while ensuring only one thread fetches a new token at a time.

§Example

use crate::OAuthTokenProvider;

let provider = OAuthTokenProvider::new("client_id".to_string(), "client_secret".to_string());

// Get or fetch a token (sync)
let token = provider.get_or_fetch(|| {
    // Your token fetching logic here
    // Returns (access_token, expires_in_seconds)
    Ok(("token".to_string(), Some(3600)))
})?;

// Get or fetch a token (async)
let token = provider.get_or_fetch_async(|| async {
    // Your async token fetching logic here
    Ok(("token".to_string(), Some(3600)))
}).await?;

Implementations§

Source§

impl OAuthTokenProvider

Source

pub fn new(client_id: String, client_secret: String) -> Self

Creates a new OAuthTokenProvider with the given credentials.

Source

pub fn client_id(&self) -> &str

Returns the client ID.

Source

pub fn client_secret(&self) -> &str

Returns the client secret.

Source

pub fn set_token(&self, access_token: String, expires_in: u64)

Sets the cached access token and its expiration time.

The expires_in parameter is the number of seconds until the token expires. A buffer is applied to refresh before actual expiration.

Source

pub fn get_token(&self) -> Option<String>

Returns the cached access token if it’s still valid.

Returns None if the token is expired or not set.

Source

pub fn get_or_fetch<F, E>(&self, fetch_func: F) -> Result<String, E>
where F: FnOnce() -> Result<(String, u64), E>,

Returns a valid token, fetching a new one if necessary (synchronous version).

The fetch_func is called at most once even if multiple threads call get_or_fetch concurrently when the token is expired. It should return (access_token, expires_in_seconds).

§Arguments
  • fetch_func - A function that fetches a new token. Returns Result<(String, u64), E> where the tuple contains (access_token, expires_in_seconds).
§Example
let token = provider.get_or_fetch(|| {
    // Call your OAuth endpoint here (sync)
    let response = auth_client.get_token(&provider.client_id(), &provider.client_secret())?;
    Ok((response.access_token, response.expires_in.unwrap_or(3600)))
})?;
Source

pub async fn get_or_fetch_async<F, Fut, E>( &self, fetch_func: F, ) -> Result<String, E>
where F: FnOnce() -> Fut, Fut: Future<Output = Result<(String, u64), E>>,

Returns a valid token, fetching a new one if necessary (async version).

This is the async version of get_or_fetch for use with async token fetching. The fetch_func is called at most once even if multiple tasks call get_or_fetch_async concurrently when the token is expired.

§Arguments
  • fetch_func - An async function that fetches a new token. Returns Result<(String, u64), E> where the tuple contains (access_token, expires_in_seconds).
§Example
let token = provider.get_or_fetch_async(|| async {
    // Call your OAuth endpoint here (async)
    let response = auth_client.get_token(&provider.client_id(), &provider.client_secret()).await?;
    Ok((response.access_token, response.expires_in.unwrap_or(3600)))
}).await?;
Source

pub fn needs_refresh(&self) -> bool

Returns true if the token needs to be refreshed.

This is useful for proactively refreshing tokens before they expire.

Source

pub fn reset(&self)

Clears the cached token.

This can be used to force a token refresh on the next request.

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> 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: Sized + 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: Sized + 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, 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<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