Skip to main content

Crate fastauth_plugin_api_key

Crate fastauth_plugin_api_key 

Source
Expand description

API keys for fastauth: per-user keys with expiry, usage limits that refill, per-key rate limits and permissions. The routes, JSON and error codes match Better Auth’s apiKey plugin, so its apiKeyClient works unchanged.

Only the SHA-256 of a key is stored; /api-key/create returns the key once. With .sessions(true), a request carrying a key in x-api-key (or the configured header) gets a session for the key’s owner that exists only for that request, so every Session<AppAuth> extractor accepts API keys with no handler changes. Each such request counts against the key’s rate limit (10 per day by default; see ApiKeys::rate_limit).

use fastauth_core::prelude::*;
use fastauth_plugin_api_key::{ApiKeys, ApiKeysExt, CreateApiKeyInput};

let auth: Auth<MemoryAdapter, (), plugins![ApiKeys]> = FastAuth::builder()
    .secret(Secret::from_bytes(vec![1u8; 32]))
    .base_url("http://localhost:3000")
    .database(MemoryAdapter::new())
    .email_password(EmailPassword::default())
    .plugin(ApiKeys::new().default_prefix("ak_"))
    .build()?;
let created = auth
    .api_keys()
    .create(CreateApiKeyInput {
        name: Some("ci".into()),
        user_id: Some(user.id.clone()),
        ..Default::default()
    })
    .await?;
assert!(created.key.starts_with("ak_"));

let verified = auth.api_keys().verify(&created.key, None).await?;
assert!(verified.valid);

Without the plugin registered, auth.api_keys() doesn’t compile:

ⓘ
use fastauth_core::prelude::*;
use fastauth_plugin_api_key::ApiKeysExt;

let auth: Auth<MemoryAdapter> = FastAuth::builder()
    .secret(Secret::from_bytes(vec![1u8; 32]))
    .base_url("http://localhost:3000")
    .database(MemoryAdapter::new())
    .build()
    .unwrap();
let _keys = auth.api_keys();

Fields that change what a key may do (remaining, refill*, rateLimit*, permissions) are server-only: over HTTP they answer SERVER_ONLY_PROPERTY, through auth.api_keys() they are accepted. /api-key/verify and /api-key/delete-all-expired-api-keys have no HTTP route, as in Better Auth.

Structs§

ApiKey
A row of apikey. Only the SHA-256 of the key is stored; the key itself is returned once, by /api-key/create.
ApiKeyCreated
Emitted when a key is created.
ApiKeyDeleted
Emitted when a key is deleted through /api-key/delete.
ApiKeyList
{ "apiKeys": [..], "total": n, "limit": .., "offset": .. }.
ApiKeyView
An API key as clients see it: every column except the hash, camelCase, with the owner as referenceId (and userId) like Better Auth.
ApiKeys
The API key plugin: .plugin(ApiKeys::new().default_prefix("ak_")).
ApiKeysApi
Calls the API key endpoints without HTTP, as the server: server-only fields are accepted, and user_id names the owner when no session is passed with headers.
CreateApiKey
POST /api-key/create.
CreateApiKeyInput
The body of /api-key/create. Fields marked server-only answer SERVER_ONLY_PROPERTY when they come from a client.
CreatedApiKey
The created key plus the full key, the only time it is shown.
DeleteAllExpiredApiKeys
/api-key/delete-all-expired-api-keys. Server-only, like Better Auth.
DeleteApiKey
POST /api-key/delete.
DeleteApiKeyInput
The body of /api-key/delete.
DeleteExpiredOutput
{ "success": true, "error": null }.
GetApiKey
GET /api-key/get?id=...
GetApiKeyInput
The query of /api-key/get.
ListApiKeys
GET /api-key/list.
ListApiKeysInput
The query of /api-key/list.
Success
{ "success": true }.
UpdateApiKey
POST /api-key/update.
UpdateApiKeyInput
The body of /api-key/update. Absent fields are left alone. Some(None) (JSON null) clears expires_in, metadata and permissions.
VerifyApiKey
/api-key/verify. Server-only, like Better Auth: not routed over HTTP, called through auth.api_keys().verify(..).
VerifyApiKeyInput
The input of /api-key/verify.
VerifyError
Why verification failed: Better Auth’s { "message", "code" }, plus details.tryAgainIn (milliseconds) for RATE_LIMITED.
VerifyOutput
{ "valid": true, "error": null, "key": {..} }, or valid: false with an error and key: null.

Enums§

ApiKeyError
Why an API key request failed. Codes, messages and statuses match Better Auth’s apiKey plugin.
SortDirection
Sort order for /api-key/list.

Traits§

ApiKeysExt
auth.api_keys(): the server API. Only compiles on an Auth with ApiKeys registered.

Type Aliases§

Permissions
What a key may do: resource name to allowed actions, { "files": ["read", "write"] }.