Skip to main content

Module auth

Module auth 

Source
Expand description

API-key and HTTP Basic authentication middleware

Small, dependency-free authentication for service-to-service calls, admin endpoints and internal tools. Secrets are compared in constant time against every configured entry (no early exit that would show which key was close), failures answer 401 with WWW-Authenticate, and the name of the authenticated caller is stored for handlers:

use ullun::auth::{ApiKeyAuth, BasicAuth};
use ullun::prelude::*;

App::new()
    .group("/internal", |g| {
        g.middleware(ApiKeyAuth::new().key("billing-service", "k_live_9c1e7a"))
            .get("/who", |req: Request| async move {
                Ok(Response::text(req.principal().unwrap_or("nobody").to_string()))
            })
    })
    .group("/admin", |g| {
        g.middleware(BasicAuth::new("admin area").user("ops", "correct horse battery staple"))
            .get("/", |_req: Request| async { Ok(Response::text("welcome")) })
    })
    .run("127.0.0.1:3000")
    .await
    .unwrap();

Keys and passwords live in memory as given: load them from the environment or a secret store, never hard-code real ones. Basic credentials are only protected by TLS. For per-user passwords stored in a database use BasicAuth::verify_with and a password hash (argon2, bcrypt) of your choice. Failed attempts are not rate limited here: put a RateLimiter in front.

Structsยง

ApiKeyAuth
Authenticate callers by a secret in a request header
BasicAuth
HTTP Basic authentication (RFC 7617)
Principal
The authenticated caller, stored in Request::extensions