OAuth2 Flow
The OAuth2 Authorization Code Grant is the most common flow for web applications to authenticate users via third-party providers like GitHub, Google, or Discord.
Overview
Authkestra's OAuth2Flow handles the complete authorization code
grant process, including state management, code exchange, and user info retrieval.
Authorization Code Grant
How It Works
- User clicks "Login with Provider"
- Your app redirects to the provider's authorization endpoint
- User authenticates and authorizes your app
- Provider redirects back with an authorization code
- Your app exchanges the code for tokens
- Your app fetches user info using the access token
- Session is created and user is logged in
Automatic Routes
When you call .authkestra_routes(), Authkestra automatically registers
routes for each provider: /auth/{provider} (login),
/auth/{provider}/callback (callback) and /auth/logout (logout).
You can pass scope and success_url as query parameters to the login route to override defaults:
/auth/github?scope=read:user&success_url=/dashboard
Implementation
Integrating OAuth2 involves configuring a provider and adding the OAuth2Flow to your Authkestra instance.
// 1. Configure the Provider
let github = GithubProvider::new(client_id, client_secret, redirect_uri);
// 2. Build Authkestra with OAuth2 flow
let authkestra = Authkestra::builder()
.provider(OAuth2Flow::new(github))
.session_store(session_store)
.session_config(SessionConfig::default()) // Optional: customize session
.build();
// 3. Register Routes (Axum example)
let app = Router::new()
.merge(authkestra.axum_router())
.with_state(AuthkestraState::from(authkestra));Full Examples
For complete working implementations including server setup and configuration, see the following examples:
PKCE Enhancement
PKCE (Proof Key for Code Exchange) adds an extra layer of security to the OAuth flow, preventing authorization code interception attacks.
use authkestra_flow::OAuth2Flow;
// PKCE is enabled by default
// For public clients (SPAs), PKCE is essential
let flow = OAuth2Flow::new(provider);
let spa_flow = OAuth2Flow::new(provider)
.with_pkce(false) // Disable it if you know what you are doing
.with_scopes(vec!["read:user", "user:email"]);When to use PKCE
Always use PKCE for:
- Single-page applications (SPAs)
- Mobile applications
- Any public client that can't securely store a client secret
