Skip to content

Authentication ​

With the jwt feature, Auth<C> verifies a bearer JWT, decodes its claims into C and documents everything that goes with it.

toml
axum-autodoc = { version = "0.2", features = ["jwt"] }

Keys in state ​

Auth<C> finds the keys through FromRef, so they live in your state like any other dependency:

rust
#[derive(Clone)]
struct AppState {
    jwt: JwtKeys,
}

impl FromRef<AppState> for JwtKeys {
    fn from_ref(state: &AppState) -> Self {
        state.jwt.clone()
    }
}

JwtKeys::hs256(secret) builds HMAC keys and jwt.sign(&claims) issues a token. JwtKeys::hmac(secret, algorithm) picks HS384 or HS512.

Asymmetric keys ​

With RSA, ECDSA or Ed25519 keys, a service that only checks tokens never holds the private key. The issuer builds keys from both PEM files and a verifier from the public one:

rust
fn issuer_keys(private_pem: &[u8], public_pem: &[u8]) -> Result<JwtKeys, InvalidJwtSecret> {
    JwtKeys::rsa_pem(private_pem, public_pem, Algorithm::RS256)
}

fn verifier_keys(public_pem: &[u8]) -> Result<JwtKeys, InvalidJwtSecret> {
    JwtKeys::rsa_verifier_pem(public_pem, Algorithm::RS256)
}
FamilyIssuer and verifierVerifier only
RSArsa_pem(private, public, algorithm)rsa_verifier_pem(public, algorithm)
ECDSAec_pem(private, public, algorithm)ec_verifier_pem(public, algorithm)
Ed25519ed_pem(private, public)ed_verifier_pem(public)

The Algorithm comes from axum_autodoc::jsonwebtoken, and an algorithm of another family than the key is refused with InvalidJwtSecret. with_validation works on every kind. Calling sign on a verifier-only value returns SignTokenError, and Auth<C> works the same whatever the keys are. The complete program is examples/jwt_keys.rs.

Check who the token is for ​

The default Validation checks the signature and exp, but not who the token is for. Set the audience and issuer you expect:

rust
let state = AppState {
    jwt: JwtKeys::hs256(b"change-me")?.with_validation(|validation| {
        validation.set_audience(&["user-api"]);
        validation.set_issuer(&["https://auth.example.com"]);
    }),
};

Required and optional ​

rust
#[api(summary = "Create a user")]
async fn create_user(Auth(_claims): Auth<Claims>, Body(body): Body<NewUser>) -> Created<User> {
    Created(User {
        id: 1,
        name: body.name,
        nickname: Some(body.email),
    })
}

#[api(summary = "Who am I", description = "Works with or without a token")]
async fn me(auth: Option<Auth<Claims>>) -> Json<Option<String>> {
    Json(auth.map(|Auth(claims)| claims.sub))
}
RequestAuth<C>Option<Auth<C>>
valid bearer tokenclaimsSome(claims)
no Authorization header401None
a scheme other than Bearer401None
invalid or expired bearer token401401

What gets documented ​

  • a bearerAuth security scheme (HTTP bearer, JWT),
  • security: [{ bearerAuth: [] }] on routes with Auth<C>,
  • security: [{}, { bearerAuth: [] }] on routes with Option<Auth<C>> and nothing that requires security (a route that also takes Auth<C>, in either order, gets [{ bearerAuth: [] }]),
  • an explicit security: [] on every public route once any route needs auth,
  • the 401 response.

How security requirements combine ​

An operation's security is a list of alternatives: any one object in it is enough, and every scheme inside one object is needed. The list is decided once per operation, whatever the order of the handler's arguments:

  • Required schemes go into one object. A required input (Auth<C>, an extractor whose describe calls cx.security_scheme or cx.require_security), a route's .detail(Detail::new().security(..)) and a group's .guard(..) each add their scheme to it. Auth<C> beside the ApiKey extractor below gives [{ apiKeyAuth: [], bearerAuth: [] }]: the request needs both.
  • Either sides and Option are alternatives. Each side of an Either, and for an Option<T> both T and nothing, is a separate object, and the required schemes are added to every one of them. Either<Auth<C>, ApiKey> alone gives [{ apiKeyAuth: [] }, { bearerAuth: [] }]; with .security("tenant") on the route it gives [{ apiKeyAuth: [], tenant: [] }, { bearerAuth: [], tenant: [] }].
  • The anonymous {} is left only when nothing is required. An alternative that needs no security holds just the required schemes, so Option<Auth<C>> alone gives [{}, { bearerAuth: [] }], and with .security("apiKey") on the route [{ apiKey: [] }, { apiKey: [], bearerAuth: [] }].
  • Order. Objects with fewer schemes come first, then by scheme name, and a duplicate is dropped.

A public route keeps security: [].

Nothing leaks

Missing and invalid tokens get 401 with WWW-Authenticate: Bearer and the same body whatever the reason, so the response never says why a token was refused.

API keys ​

Auth<C> documents a bearer scheme. For a key in a header, a query parameter or a cookie, write the extractor and declare the scheme in its DocInput:

rust
struct ApiKey;

#[derive(Clone)]
struct ExpectedApiKey(String);

fn same_bytes(left: &[u8], right: &[u8]) -> bool {
    let mut difference = left.len() ^ right.len();
    for index in 0..left.len().max(right.len()) {
        let a = left.get(index).copied().unwrap_or(0);
        let b = right.get(index).copied().unwrap_or(0);
        difference |= usize::from(a ^ b);
    }
    difference == 0
}

impl<S> FromRequestParts<S> for ApiKey
where
    S: Send + Sync,
    ExpectedApiKey: FromRef<S>,
{
    type Rejection = StatusCode;

    fn from_request_parts(
        parts: &mut Parts,
        state: &S,
    ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
        let expected = ExpectedApiKey::from_ref(state);
        let key = parts
            .headers
            .get("x-api-key")
            .filter(|value| same_bytes(value.as_bytes(), expected.0.as_bytes()))
            .map(|_| Self)
            .ok_or(StatusCode::UNAUTHORIZED);
        ready(key)
    }
}

impl DocInput for ApiKey {
    fn describe(cx: &mut DocContext<'_>) {
        cx.security_scheme(
            "apiKeyAuth",
            SecurityScheme::ApiKey {
                name: "x-api-key".to_string(),
                location: ParameterLocation::Header,
            },
        );
        cx.response(401, "missing or wrong API key");
    }
}

Routes that take ApiKey get security: [{ apiKeyAuth: [] }], and the scheme appears under components.securitySchemes. ParameterLocation is in axum_autodoc::openapi, and SecurityScheme at the crate root. The extractor compares the header with the key in the router state (FromRef) in constant time and answers 401 on a mismatch; a real service would look the key up in its own store the same way.

Released under the MIT or Apache-2.0 license.