Expand description
§mwoauth
mwoauth is a framework-independent MediaWiki OAuth 2.0 client with optional adapters for Rocket, Axum, and Actix Web. No framework is enabled by default, and the core can be used directly with custom applications or adapters.
- License: GPL-3.0-or-later
- Minimum supported Rust version (MSRV): 1.93
- Recommended callback path:
/oauth/callback
§Installation
§Core only
[dependencies]
mwoauth = { version = "0.1.0-alpha.2", default-features = false }§Rocket
[dependencies]
mwoauth = { version = "0.1.0-alpha.2", features = ["rocket"] }§Axum
[dependencies]
mwoauth = { version = "0.1.0-alpha.2", features = ["axum"] }§Actix Web
[dependencies]
mwoauth = { version = "0.1.0-alpha.2", features = ["actix"] }§Multiple frameworks
Framework features are additive and can be enabled together:
[dependencies]
mwoauth = { version = "0.1.0-alpha.2", features = ["rocket", "axum", "actix"] }§Legacy callback alias
Combine legacy-callback with any framework feature to add /auth as a compatibility alias:
[dependencies]
mwoauth = { version = "0.1.0-alpha.2", features = ["rocket", "legacy-callback"] }legacy-callback alone is a supported no-op and does not enable a framework.
§Features
| Feature | Default | Functionality |
|---|---|---|
rocket | No | Rocket fairing, routes, private-cookie sessions, and request guards |
axum | No | Axum router, shared state, private-cookie sessions, and extractors |
actix | No | Actix route configuration, actix-session, and extractors |
legacy-callback | No | Adds /auth to every enabled adapter |
Enabling one adapter does not enable another adapter or its dependencies. Framework APIs are available through mwoauth::rocket, mwoauth::axum, and mwoauth::actix; shared OAuth types remain at the crate root.
§Register a MediaWiki OAuth consumer
Register an OAuth 2.0 consumer on the target wiki. For Wikimedia wikis, use:
https://meta.wikimedia.org/wiki/Special:OAuthConsumerRegistration/propose
Select OAuth 2.0 and register the exact callback URL used by the application. New applications should use:
https://your-app.example/oauth/callbackMediaWiki redirects to that URL with code and state query parameters. The callback path belongs to your application; it is not imposed by MediaWiki. /auth is supported only as a legacy alias when legacy-callback is enabled.
§Shared configuration and core API
MwOAuthConfig contains:
wiki_url: absolute HTTP(S) wiki URL. An API URL such ashttps://meta.wikimedia.org/w/api.php, arest.phpURL, or the containing wiki path is normalized to the REST base.client_id: non-empty OAuth client identifier.client_secret: secret for confidential clients; public clients omit it and use PKCE.redirect_uri: exact registered callback URI.with_registered_redirect()omits the parameter and lets MediaWiki use the registered callback.user_agent: non-empty valid HTTP header value. Wikimedia requests should follow the Wikimedia User-Agent policy.request_timeout: bounded timeout for each provider request; the default is 15 seconds.
Configuration is validated when it is constructed and again by MwOAuthClient::new. Invalid URLs, empty credentials, unsafe redirect fragments, invalid User-Agent values, and zero timeouts return typed errors without exposing secrets.
use mwoauth::{MwOAuthClient, MwOAuthConfig};
use url::Url;
let config = MwOAuthConfig::confidential(
Url::parse("https://meta.wikimedia.org/w/api.php")?,
"CLIENT_ID",
"CLIENT_SECRET",
Url::parse("https://your-app.example/oauth/callback")?,
"your-app/1.0 (contact@example.com)",
)?;
let client = MwOAuthClient::new(config)?;The core exports authorization URL generation, state and PKCE-S256 handling, code exchange, token refresh, profile fetching, OAuthToken, UserProfile, AuthenticatedUser, Error, ErrorKind, and the framework-independent SessionStore trait.
§Rocket
Construct the same shared MwOAuthConfig and MwOAuthClient used by the other adapters, then attach RocketOAuth::new(client). The fairing mounts /oauth/login, /oauth/callback, and /oauth/logout.
use mwoauth::rocket::RocketOAuth;
use mwoauth::{MwOAuthClient, MwOAuthConfig, UserGuard};
use url::Url;
#[get("/profile")]
fn profile(user: UserGuard) -> String {
user.profile().username().to_owned()
}
#[launch]
fn rocket() -> _ {
let config = MwOAuthConfig::confidential(
Url::parse("https://meta.wikimedia.org/w/api.php").unwrap(),
"CLIENT_ID",
"CLIENT_SECRET",
Url::parse("https://your-app.example/oauth/callback").unwrap(),
"your-app/1.0",
).unwrap();
let client = MwOAuthClient::new(config).unwrap();
rocket::build()
.attach(RocketOAuth::new(client))
.mount("/", routes![profile])
}Explicit Rust configuration is the primary API. Applications that prefer Rocket Figment can load the same MwOAuthConfig with mwoauth::rocket::config_from_figment(rocket.figment(), user_agent) before attaching RocketOAuth::new(client).
The Figment helper supports Rocket.toml:
[default]
secret_key = "GENERATE_AND_STORE_A_SECRET_KEY"
[default.mwoauth]
client_id = "CLIENT_ID"
client_secret = "CLIENT_SECRET"
wiki_url = "https://meta.wikimedia.org/w/api.php"
# Optional; omit to use the callback registered at MediaWiki.
redirect_uri = "https://your-app.example/oauth/callback"Or use Rocket’s environment configuration. The names intentionally remain compatible with the original crate:
ROCKET_SECRET_KEY=SECRET_KEY
ROCKET_MWOAUTH='{client_id="CLIENT_ID",client_secret="CLIENT_SECRET",wiki_url="https://meta.wikimedia.org/w/api.php",redirect_uri="https://your-app.example/oauth/callback"}'Flat variables are also supported:
ROCKET_SECRET_KEY=SECRET_KEY
ROCKET_MWOAUTH_CLIENT_ID=CLIENT_ID
ROCKET_MWOAUTH_CLIENT_SECRET=CLIENT_SECRET
ROCKET_MWOAUTH_WIKI_URL=https://meta.wikimedia.org/w/api.php
ROCKET_MWOAUTH_REDIRECT_URI=https://your-app.example/oauth/callbackROCKET_MWOAUTH_REDIRECT_URI is optional. ROCKET_SECRET_KEY is required for encrypted private cookies and must remain stable across instances and restarts. The ROCKET_MWOAUTH_* names are retained by config_from_figment; they are no longer loaded implicitly by the fairing.
Use UserGuard for required authentication and Option<UserGuard> for the original soft-authentication behavior. For new code that must not hide provider, network, or internal failures, use OptionalUserGuard; it converts only missing or expired authentication to None.
See examples/rocket.rs.
§Axum
Construct AxumOAuthState from the shared client and an encryption Key, compose routes() with the application router, and provide the state. For a standalone OAuth router, use oauth_router(state) instead:
use axum::{middleware::from_extractor_with_state, routing::get};
use mwoauth::axum::{AxumOAuthState, AxumUser, Key, routes};
let state = AxumOAuthState::new(client, Key::generate());
let app = routes()
.route("/profile", get(|user: AxumUser| async move {
user.profile().username().to_owned()
}))
.route(
"/protected",
get(|| async { "protected" }).route_layer(
from_extractor_with_state::<AxumUser, _>(state.clone()),
),
)
.layer(axum::middleware::from_fn_with_state(
state.clone(), mwoauth::axum::refresh_session,
))
.with_state(state);AxumUser implements FromRequestParts. Use it directly for required authentication, Option<AxumUser> for soft authentication, or with from_extractor_with_state for route protection. Larger application state types can embed AxumOAuthState by implementing FromRef for both AxumOAuthState and the cookie Key.
Install refresh_session on the application router to renew expired access tokens and persist rotated tokens in the encrypted cookie. Without this layer, extractors reject expired access tokens with HTTP 401.
mwoauth::axum::CookieConfig controls cookie domain, path, Secure, HttpOnly, SameSite, and optional maximum age. Defaults are Secure, HttpOnly, SameSite=Lax, path /, no domain, and session-cookie expiration. Disable Secure only for local HTTP development.
See examples/axum.rs.
§Actix Web
Install ActixOAuthState with App::app_data, wrap the application in session middleware, and call configure:
use actix_web::{App, cookie::Key, web};
use mwoauth::actix::{
ActixOAuthState, CookieConfig, configure, cookie_session_middleware,
};
let state = web::Data::new(ActixOAuthState::new(client));
let app = App::new()
.app_data(state)
.wrap(cookie_session_middleware(Key::generate(), CookieConfig::default()))
.configure(configure);ActixUser is the required FromRequest guard. Option<ActixUser> is supported for conventional soft extraction, while OptionalActixUser is recommended when session-backend failures must not be hidden.
The convenience middleware uses CookieSessionStore with private encryption. mwoauth::actix::CookieConfig controls cookie name, domain, path, Secure, HttpOnly, SameSite, and optional maximum age. Applications may instead install SessionMiddleware with a server-side actix-session store; the routes and extractors continue to work without changes.
See examples/actix.rs.
§Session security model
OAuth sessions must resist disclosure, tampering, fixation, and callback-state substitution. The adapters retain only pending state, a PKCE verifier, flow expiry, authenticated profile, and OAuth tokens. Pending flows expire after 10 minutes. Cookie-backed flows are removed from the browser on a callback, but a saved copy of the original cookie can be replayed until expiry. Use a server-side SessionStore with atomic consumption when a callback attempt must be terminal across requests. Authenticated sessions have a fixed 24-hour maximum lifetime; token refresh does not extend it.
Rocket and Axum encrypt and authenticate client-side cookies. Actix’s convenience middleware uses private encrypted cookie storage; a server-side store may use a signed cookie only when it contains an opaque session identifier. Cookie formats and keys are intentionally adapter-specific.
Generate cookie keys with a cryptographically secure generator, store them outside source control, load them at startup, and reuse them across application instances. Invalid key material must fail during key construction or startup; the crate never falls back to unsigned or unencrypted storage. Key rotation invalidates existing sessions unless the chosen framework or backend explicitly supports a bounded old-key migration.
Use HTTPS with Secure, HttpOnly, and SameSite=Lax. Client-side cookies cannot provide immediate global revocation after a cookie has been copied; use Actix with a server-side store or implement a revocable core SessionStore when immediate revocation is required.
Required guards return HTTP 401 for absent, malformed, tampered, or expired authentication. Callback validation errors return HTTP 400, provider/network failures return HTTP 502, and internal configuration/session failures return HTTP 500. Browser responses are generic. Secret-bearing values redact their Debug output.
§Legacy callback
legacy-callback adds /auth as a compatibility-only callback route to every enabled framework adapter. New applications should register /oauth/callback. Enabling legacy-callback without a framework is a valid no-op.
§Supported versions and maintenance
mwoauth 0.1 supports Rust 1.93 and newer, Rocket 0.5, Axum 0.8 with axum-extra 0.12, and Actix Web 4 with actix-session 0.11. CI tests the declared MSRV and current stable Rust. Patch releases may update dependencies without raising MSRV; an MSRV increase requires a documented minor release. Security fixes are applied to the latest compatible release line.
§License and provenance
mwoauth originally started as a fork of rocket_mwoauth.
The project has since been substantially redesigned and rewritten: the OAuth flow was moved into a framework-independent core, rocket_oauth2 was removed, and new Rocket, Axum, and Actix Web adapters were implemented. It nevertheless retains its upstream attribution and is distributed under GPL-3.0-or-later. See LICENSE, NOTICE, and CHANGELOG.md for details.
Re-exports§
pub use rocket::OptionalUserGuard;rocketpub use rocket::RocketOAuth;rocketpub use rocket::UserGuard;rocket
Modules§
Structs§
- Authenticated
User - Authenticated user information stored by framework adapters.
- Authorization
Request - Authorization URL and opaque state returned when starting a login flow.
- MwOAuth
Client - Framework-independent MediaWiki OAuth 2.0 client.
- MwOAuth
Config - Framework-independent configuration for MediaWiki OAuth 2.0.
- OAuth
Token - OAuth token response returned by MediaWiki.
- PendingO
Auth Flow - Secret data that must survive between authorization and callback requests.
- User
Profile - Information returned by MediaWiki’s OAuth profile endpoint.
Enums§
- Error
- Errors produced by the framework-independent MediaWiki OAuth flow.
- Error
Kind - Stable categories for mapping OAuth failures into framework responses.
Constants§
- DEFAULT_
FLOW_ TTL - Maximum age used for newly-created authorization flows.
- DEFAULT_
SESSION_ TTL - Maximum age used for newly-authenticated sessions.
Traits§
- Session
Store - Framework-neutral storage used by OAuth adapters.