Skip to main content

axum_oidc_client/
lib.rs

1//! # axum-oidc-client
2//!
3//! A comprehensive OAuth2/OIDC authentication library for Axum web applications with PKCE support.
4//!
5//! ## Features
6//!
7//! - **OAuth2/OIDC Authentication**: Full support for OAuth2 and OpenID Connect protocols
8//! - **PKCE Support**: Implements Proof Key for Code Exchange (RFC 7636) for enhanced security
9//! - **Automatic Token Refresh**: Seamlessly refreshes expired ID tokens and access tokens using OAuth2 refresh token flow
10//! - **Flexible Caching**: Pluggable cache backends with built-in Redis support
11//! - **Session Management**: Secure session handling with encrypted cookies
12//! - **Logout Handlers**: Support for both standard and OIDC logout flows
13//! - **Type-safe Extractors**: Convenient extractors for authenticated users and sessions
14//! - **Custom CA Certificates**: Support for custom certificate authorities
15//!
16//! ## Quick Start
17//!
18//! ```rust,no_run
19//! use axum::{Router, routing::get};
20//! use axum_oidc_client::{
21//!     auth::{AuthLayer, CodeChallengeMethod},
22//!     auth_builder::OAuthConfigurationBuilder,
23//!     auth_cache::AuthCache,
24//!     logout::handle_default_logout::DefaultLogoutHandler,
25//! };
26//! use std::sync::Arc;
27//!
28//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
29//! // Build OAuth configuration
30//! let config = OAuthConfigurationBuilder::default()
31//!     .with_authorization_endpoint("https://accounts.google.com/o/oauth2/auth")
32//!     .with_token_endpoint("https://oauth2.googleapis.com/token")
33//!     .with_client_id("your-client-id")
34//!     .with_client_secret("your-client-secret")
35//!     .with_redirect_uri("http://localhost:8080/auth/callback")
36//!     .with_private_cookie_key("your-secret-key")
37//!     .with_scopes(vec!["openid", "email", "profile"])
38//!     .with_code_challenge_method(CodeChallengeMethod::S256)
39//!     .build()?;
40//!
41//! // Create a cache implementation (using Redis in this example)
42//! # #[cfg(feature = "redis")]
43//! let cache: Arc<dyn AuthCache + Send + Sync> = Arc::new(
44//!     axum_oidc_client::redis::AuthCache::new("redis://127.0.0.1/", 3600)
45//! );
46//!
47//! // Create logout handler
48//! let logout_handler = Arc::new(DefaultLogoutHandler);
49//!
50//! // Build your application
51//! let app = Router::new()
52//!     .route("/", get(|| async { "Hello, World!" }))
53//!     .layer(AuthLayer::new(Arc::new(config), cache, logout_handler));
54//!
55//! # Ok(())
56//! # }
57//! ```
58//!
59//! ## Module Overview
60//!
61//! - [`auth`]: Core authentication types and the `AuthLayer` for Axum
62//! - [`auth_builder`]: Builder pattern for constructing OAuth configurations
63//! - [`auth_cache`]: Cache trait and implementations for storing auth state
64//! - [`auth_session`]: Session management and token handling
65//! - [`extractors`]: Type-safe extractors for accessing authenticated user data with automatic ID token and access token refresh
66//! - [`logout`]: Logout handler implementations (default and OIDC)
67//! - [`errors`]: Error types used throughout the library
68//! - [`redis`]: Redis-based cache implementation (requires `redis` feature)
69//!
70//! ## Automatic ID Token and Access Token Refresh
71//!
72//! The library automatically refreshes expired ID tokens and access tokens using the OAuth2 refresh token flow.
73//! When using the provided extractors (`AccessToken`, `IdToken`, `AuthSession`), token expiration
74//! is checked on each request. If tokens are expired, the library:
75//!
76//! 1. Uses the refresh token to request new ID token and access token from the provider
77//! 2. Updates the session with the new tokens and expiration time
78//! 3. Saves the updated session to the cache
79//! 4. Returns the fresh token to your handler
80//!
81//! This happens transparently - your application code doesn't need to handle token refresh manually.
82//!
83//! ## Configuration
84//!
85//! The library uses a builder pattern for configuration. See [`auth_builder::OAuthConfigurationBuilder`]
86//! for all available options.
87//!
88//! ### Code Challenge Methods
89//!
90//! The library supports two PKCE code challenge methods:
91//! - `S256`: SHA-256 hashing (recommended, default)
92//! - `Plain`: Plain text (not recommended for production)
93//!
94//! ## Cache Backends
95//!
96//! Implement the [`auth_cache::AuthCache`] trait to create custom cache backends.
97//! Built-in implementations:
98//!
99//! - **Redis**: Available with the `redis` feature flag
100//!
101//! ## Security Considerations
102//!
103//! - Always use `S256` code challenge method in production
104//! - Use strong, randomly generated values for `private_cookie_key`
105//! - Ensure secure transport (HTTPS) for all OAuth endpoints
106//! - Configure appropriate session and token expiration times
107//! - Validate redirect URIs match your OAuth provider configuration
108//!
109//! ## Feature Flags
110//!
111//! - `redis`: Enable Redis cache backend (default TLS)
112//! - `redis-rustls`: Enable Redis with rustls for TLS
113//! - `redis-native-tls`: Enable Redis with native-tls
114//!
115//! ## Examples
116//!
117//! See the `examples/sample-server` directory for a complete working example.
118
119pub mod auth;
120pub mod auth_builder;
121pub mod auth_cache;
122mod auth_router;
123pub mod auth_session;
124pub mod errors;
125pub mod extractors;
126pub mod logout;
127
128#[cfg(any(
129    feature = "redis",
130    feature = "redis-rustls",
131    feature = "redis-native-tls"
132))]
133pub mod redis;