Expand description
§axum-oidc-client
A comprehensive OAuth2/OIDC authentication library for Axum web applications with PKCE support.
§Features
- OAuth2/OIDC Authentication: Full support for OAuth2 and OpenID Connect protocols
- PKCE Support: Implements Proof Key for Code Exchange (RFC 7636) for enhanced security
- Automatic Token Refresh: Seamlessly refreshes expired ID tokens and access tokens using OAuth2 refresh token flow
- Flexible Caching: Pluggable cache backends with built-in Redis support
- Session Management: Secure session handling with encrypted cookies
- Logout Handlers: Support for both standard and OIDC logout flows
- Type-safe Extractors: Convenient extractors for authenticated users and sessions
- Custom CA Certificates: Support for custom certificate authorities
§Quick Start
use axum::{Router, routing::get};
use axum_oidc_client::{
auth::{AuthenticationLayer, CodeChallengeMethod},
auth_builder::OAuthConfigurationBuilder,
auth_cache::AuthCache,
// `TwoTierAuthCache` requires the `moka-cache` feature (enabled by default).
cache::{TwoTierAuthCache, config::TwoTierCacheConfig},
logout::handle_default_logout::DefaultLogoutHandler,
};
use std::sync::Arc;
// Build OAuth configuration
let config = OAuthConfigurationBuilder::default()
.with_authorization_endpoint("https://accounts.google.com/o/oauth2/auth")
.with_token_endpoint("https://oauth2.googleapis.com/token")
.with_client_id("your-client-id")
.with_client_secret("your-client-secret")
.with_redirect_uri("http://localhost:8080/auth/callback")
.with_private_cookie_key("your-secret-key")
.with_scopes(vec!["openid", "email", "profile"])
.with_code_challenge_method(CodeChallengeMethod::S256)
.with_post_logout_redirect_uri("/")
.with_session_max_age(3600)
.build()?;
// Create an L1-only in-memory cache (requires the `moka-cache` feature).
// For Redis, enable the `redis` feature and use `axum_oidc_client::redis::AuthCache`.
let cache: Arc<dyn AuthCache + Send + Sync> = Arc::new(
TwoTierAuthCache::new(None, TwoTierCacheConfig::default())?
);
// Create logout handler
let logout_handler = Arc::new(DefaultLogoutHandler);
// Build your application
let app: Router<()> = Router::new()
.route("/", get(|| async { "Hello, World!" }))
.layer(AuthenticationLayer::new(Arc::new(config), cache, logout_handler));
§Module Overview
auth: Core authentication types and theAuthenticationLayerfor Axum (AuthLayeris kept as a backward-compatible type alias)auth_builder: Builder pattern for constructing OAuth configurationsauth_cache: Cache trait and implementations for storing auth stateauth_session: Session management and token handlingextractors: Type-safe extractors for accessing authenticated user data with automatic ID token and access token refreshlogout: Logout handler implementations (default and OIDC)errors: Error types used throughout the library- [
redis]: Redis-based cache implementation (requiresredisfeature) cache: Two-tier cache combining Moka L1 with any L2 backend (requiresmoka-cachefeature)- [
sql_cache]: SQL database cache backend (requiressql-cache-postgres,sql-cache-mysql, orsql-cache-sqlitefeature)
§Automatic ID Token and Access Token Refresh
The library automatically refreshes expired ID tokens and access tokens using the OAuth2 refresh token flow.
When using the provided extractors (AccessToken, IdToken, AuthSession), token expiration
is checked on each request. If tokens are expired, the library:
- Uses the refresh token to request new ID token and access token from the provider
- Updates the session with the new tokens and expiration time
- Saves the updated session to the cache
- Returns the fresh token to your handler
This happens transparently - your application code doesn’t need to handle token refresh manually.
§Configuration
The library uses a builder pattern for configuration. See auth_builder::OAuthConfigurationBuilder
for all available options.
§Code Challenge Methods
The library supports two PKCE code challenge methods:
S256: SHA-256 hashing (recommended, default)Plain: Plain text (not recommended for production)
§Cache Backends
Implement the auth_cache::AuthCache trait to create custom cache backends.
Built-in implementations:
- Redis: Available with the
redisfeature flag
§Security Considerations
- Always use
S256code challenge method in production - Use strong, randomly generated values for
private_cookie_key - Ensure secure transport (HTTPS) for all OAuth endpoints
- Configure appropriate session and token expiration times
- Validate redirect URIs match your OAuth provider configuration
§Feature Flags
§Top-level (default)
authentication(default) – OAuth2/OIDC middleware, session management, cache trait, builder, router, extractors, and logout handlers. Implied by every cache/backend feature.jwt(default) – JWT validation and inspection utilities.
§Cache backends (each implies authentication)
moka-cache(default) – two-tier in-process Moka L1 cacheredis– Redis cache backend (rustls TLS)redis-rustls– Redis with explicit rustls TLSredis-native-tls– Redis with native-tlssql-cache-postgres– PostgreSQL backend via sqlxsql-cache-mysql– MySQL/MariaDB backend via sqlxsql-cache-sqlite– SQLite backend via sqlxsql-cache-all– all three SQL backends at once (useful for testing)
§Examples
See the examples directory for a complete working examples.
Re-exports§
pub use authentication::builder as auth_builder;pub use authentication::cache as auth_cache;pub use authentication::session as auth_session;pub use authentication::logout;pub use authentication as auth;pub use authentication::moka as cache;
Modules§
- authentication
- Core authentication module for OAuth2/OIDC with PKCE support.
- errors
- extractors
- Type-safe extractors for accessing authenticated user data with automatic ID token and access token refresh.
- http_
client - HTTP client construction for axum-oidc-client.
- jwt