Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

API keys

We do not recommend them. Whoever has the text of a key can use it. Use a device for your own CLIs and machines, and a connected app for programs of others. Use an API key only if a program can send nothing but a fixed header.

They are off until you turn them on:

use auth_chad::api_key::ApiKeys;
use auth_chad::axum::{ApiKey, Auth, Hooks};
use auth_chad::{Authenticated, Error, Store};

fn turn_on<S: Store, H>(auth: Auth<S, H>) -> Result<Auth<S, H>, Error> {
    Ok(auth.with_api_keys(ApiKeys::new("example_", &["reports:read"])?))
}

struct App;

impl<S: Store> Hooks<S> for App {
    async fn may_create_key(&self, _who: &Authenticated, scopes: &[&str]) -> bool {
        scopes == ["reports:read"]
    }
}

async fn reports(key: ApiKey) -> Result<String, auth_chad::axum::Refused> {
    if !key.0.has_scope("reports:read") {
        return Err(auth_chad::Code::Forbidden.into());
    }
    Ok(format!("reports of {}", key.user()?))
}
CallDoes
POST /auth/keys with name, scopes, lifetime in secondsMakes a key. Needs a fresh login. secret is in the answer once
GET /auth/keysLists them, with the last use and its address (up to five minutes old)
DELETE /auth/keys/{id}Ends one

In the browser: newApiKey({ name, scopes, days }), apiKeys(), endApiKey(id). Show the secret once, and keep it nowhere.

  • A key lives at most 90 days, and has no renewal. Make the next one before it ends.
  • Only ApiKey accepts a key. FirstParty, InPerson, FreshLogin and ConnectedApp refuse it, and so does the whole account API. A route for both a user and a key decides with Caller.
  • ApiKey is the user that made the key, not the user in person. Let a key read before you let it write.
  • Tell your users: never in a page, an app or a repository. The prefix lets secret scanners find it. Never change the prefix: every key stops working.
  • Policy.key_bound refuses every key. Without with_api_keys, no key works.
  • Do not log the Authorization header.