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. - ApiKey
Created - Emitted when a key is created.
- ApiKey
Deleted - Emitted when a key is deleted through
/api-key/delete. - ApiKey
List { "apiKeys": [..], "total": n, "limit": .., "offset": .. }.- ApiKey
View - An API key as clients see it: every column except the hash, camelCase, with the owner
as
referenceId(anduserId) like Better Auth. - ApiKeys
- The API key plugin:
.plugin(ApiKeys::new().default_prefix("ak_")). - ApiKeys
Api - Calls the API key endpoints without HTTP, as the server: server-only fields are accepted,
and
user_idnames the owner when no session is passed withheaders. - Create
ApiKey POST /api-key/create.- Create
ApiKey Input - The body of
/api-key/create. Fields marked server-only answerSERVER_ONLY_PROPERTYwhen they come from a client. - Created
ApiKey - The created key plus the full
key, the only time it is shown. - Delete
AllExpired ApiKeys /api-key/delete-all-expired-api-keys. Server-only, like Better Auth.- Delete
ApiKey POST /api-key/delete.- Delete
ApiKey Input - The body of
/api-key/delete. - Delete
Expired Output { "success": true, "error": null }.- GetApi
Key GET /api-key/get?id=...- GetApi
KeyInput - The query of
/api-key/get. - List
ApiKeys GET /api-key/list.- List
ApiKeys Input - The query of
/api-key/list. - Success
{ "success": true }.- Update
ApiKey POST /api-key/update.- Update
ApiKey Input - The body of
/api-key/update. Absent fields are left alone.Some(None)(JSONnull) clearsexpires_in,metadataandpermissions. - Verify
ApiKey /api-key/verify. Server-only, like Better Auth: not routed over HTTP, called throughauth.api_keys().verify(..).- Verify
ApiKey Input - The input of
/api-key/verify. - Verify
Error - Why verification failed: Better Auth’s
{ "message", "code" }, plusdetails.tryAgainIn(milliseconds) forRATE_LIMITED. - Verify
Output { "valid": true, "error": null, "key": {..} }, orvalid: falsewith an error andkey: null.
Enums§
- ApiKey
Error - Why an API key request failed. Codes, messages and statuses match Better Auth’s
apiKeyplugin. - Sort
Direction - Sort order for
/api-key/list.
Traits§
- ApiKeys
Ext auth.api_keys(): the server API. Only compiles on anAuthwithApiKeysregistered.
Type Aliases§
- Permissions
- What a key may do: resource name to allowed actions,
{ "files": ["read", "write"] }.