Trait TokenProvider
pub trait TokenProvider:
Send
+ Sync
+ 'static {
// Required method
fn get_token(&self) -> Result<String, TokenError>;
}Expand description
Any source of a bearer token: fetched from an IdP, forwarded from an upstream request, or static (e.g. for testing).
§Object safety
This trait is not object-safe because each implementor returns a concrete type
from get_token. If you need to select a provider at runtime, use an enum:
use rust_auth_lib::{TokenProvider, TokenError, ForwardedToken};
use rust_auth_lib::keycloak::KeycloakClientCredentialsProvider;
// requires the jwks-url feature
#[derive(Clone)]
pub enum AnyTokenProvider {
Keycloak(KeycloakClientCredentialsProvider),
Forwarded(ForwardedToken),
}
impl TokenProvider for AnyTokenProvider {
fn get_token(&self) -> Result<String, TokenError> {
match self {
Self::Keycloak(p) => p.get_token(),
Self::Forwarded(p) => p.get_token(),
}
}
}§Error type
get_token() returns TokenError rather than the broader AuthError
because, by convention, configuration errors should not occur at token-fetch time in the
provided implementations — the provider is already constructed and configured. This is a
design guideline for implementors, not an enforced contract; a custom implementation could
in principle surface a configuration failure here. Use ? to propagate into AuthError
where needed, since From<TokenError> for AuthError is implemented.
§Bounds
Send + Sync + 'static are required so that providers can be held in
long-lived contexts and passed across async task boundaries. Clone is
not required by the trait — concrete types that need it (e.g.
KeycloakClientCredentialsProvider,
ForwardedToken) implement it independently.
Required Methods§
fn get_token(&self) -> Result<String, TokenError>
fn get_token(&self) -> Result<String, TokenError>
Return the current bearer token string.
By convention, implementations should be cheap to call — ideally a lock
read with no I/O. This is not enforced by the trait; it is a design
guideline for implementors. KeycloakClientCredentialsProvider and
ForwardedToken both satisfy it on every call. FileTokenProvider
satisfies it on cache hits; on a cache miss it performs a blocking
filesystem read before updating the cache.