Custom authentication
Custom authentication lets you plug your own credential check into the gateway. Normally every request has to carry a Spanway virtual key. With custom auth, you write one small Python function that looks at the request and the credential the client sent, decides who the caller is, and hands that identity back to the gateway. The gateway then applies budgets, rate limits, model access and logging to that identity exactly as it would for a virtual key. Nobody has to issue or rotate Spanway keys for callers that already have a token from your own systems.
Custom auth needs no license. Its code ships in the enterprise modules of the gateway image, which every install has, and it runs on every request, so the function must be fast.
A real-world scenario
An internal platform team already gives each service a token that starts with corp-. Dozens of services call the gateway, and the team does not want to create and distribute a Spanway key for each one. They write a custom auth function that recognises corp- tokens, looks up which team the token belongs to in their own registry, and returns that team. Every service keeps the token it already has, and spend still lands on the right team in the Admin UI.
Steps
-
Write the function. It receives the FastAPI
Requestand the credential the client sent, and returns either aUserAPIKeyAuthobject or the plaintext value of an existing virtual key. Raise aProxyExceptionto reject the call with a status code and message of your choosing. Save the file next to yourconfig.yaml, for example ascustom_auth.py.from fastapi import Requestfrom spanway.proxy._types import ProxyException, UserAPIKeyAuthasync def user_api_key_auth(request: Request, api_key: str) -> UserAPIKeyAuth | str:if api_key.startswith("corp-"):team_id = await lookup_team_for_token(api_key)return UserAPIKeyAuth(api_key=api_key, team_id=team_id, user_id="svc-reporting")raise ProxyException(message="Invalid API key",type="invalid_request_error",param="api_key",code=401,) -
Register it in
config.yamlasmodule.function. The module path is resolved relative to the config file. Turn oncustom_auth_run_common_checksso the gateway's standard checks still run after your function.general_settings:custom_auth: custom_auth.user_api_key_authcustom_auth_run_common_checks: true -
Restart the gateway. Custom auth is read from the config file at startup and has no Admin UI control, because the function is code that lives next to your deployment.
-
Call the gateway with one of your own tokens.
curl -s http://localhost:4000/v1/chat/completions \-H "Authorization: Bearer corp-reporting-7f3a" \-H "Content-Type: application/json" \-d '{"model": "claude-sonnet", "messages": [{"role": "user", "content": "Summarise last week."}]}' -
Open Logs in the Admin UI. The request appears under the team and user your function returned, and spend accrues to that team on the Teams page.
Expected result
The call succeeds with a normal chat completion response. A token your function rejects gets the status code and message you raised, 401 Invalid API key in the example. With custom_auth_run_common_checks: true the team's budget, model allow-list and rate limits apply to the request as they would to a virtual key, and a request over budget is refused with 422 and the budget_exceeded code like any other, or 429 when spanway_settings.budget_exceeded_status_code is 429, see the error reference.
How the return value is used
Returning a UserAPIKeyAuth describes the caller directly. Fill in team_id, user_id, models or max_budget to shape what the caller may do. Returning a string maps the outside credential onto an existing virtual key. The gateway then loads that key's settings and limits from the database, which is the simplest way to give a group of outside tokens the exact permissions of one key you manage in the Admin UI.
custom_auth_run_common_checks is false by default. Without it, your function alone decides what the caller may do, and budgets, model allow-lists and rate limits stored on teams and keys in the database are not enforced for those requests. The gateway logs a warning once at startup in that case. Turn the setting on unless you deliberately handle every check yourself. The IP allow-lists on keys, teams and organizations described in IP and route allow-lists also only apply when the common checks run.
Turning custom auth off or making it a fallback
general_settings.custom_auth_settings.mode decides when your function runs. Leave it out, or set on, and your function checks every request. off keeps the function configured but skips it, so only virtual keys work, which helps while you debug the function. auto runs your function first and, when it raises, falls back to normal virtual key checking, so callers with Spanway keys keep working while your token callers use the function. With auto a rejected token is never an error by itself, it is simply checked as a key next.
general_settings:
custom_auth: custom_auth.user_api_key_auth
custom_auth_settings:
mode: auto
spanway_settings.enable_post_custom_auth_checks: true runs the gateway's own checks on the identity your function returns: the key expiry, the customer budget and block for the end_user_id you set, and, with custom_auth_run_common_checks, the key's model access. It is off by default, so only your function decides.
Related hooks
| Setting | What it lets you customise |
|---|---|
custom_key_generate | Validate or reject /key/generate requests, for example to enforce naming or budget rules. |
custom_key_update | Validate /key/update requests. |
custom_key_policy | Apply a policy function to keys at creation and update. |
custom_team_metadata_validate | Validate team metadata. |
Each takes a module.function path in general_settings, loaded the same way as custom_auth.
Errors
| What you see | Why | Fix |
|---|---|---|
The gateway fails to start and names custom_auth. | The module or function could not be imported. | Check that the file sits next to config.yaml, that the path is module.function with no .py, and that the file imports cleanly. |
| Every request is refused with the status your function raises. | The function rejects credentials it should accept, often because it expects a prefix the client does not send. | The gateway strips the Bearer prefix before calling you. Log the first characters of api_key once to confirm what arrives. |
| Admins cannot sign in to the Admin UI. | The function also runs for Admin UI requests that carry a key and rejects the session key. | Let the function fall through for keys that start with sk-, or return the string when it is a virtual key. |
The startup log warns that custom_auth_run_common_checks is not set. | Budgets and model allow-lists stored on teams and keys are not enforced for custom-auth requests. | Set general_settings.custom_auth_run_common_checks: true. |
| Requests are slow. | The function calls a remote system on every request. | Cache lookups in memory with a short TTL, or return a virtual key string so the gateway's own cache does the work. |
Related
- JWT authentication accepts tokens from your identity provider without any code of your own.
- OAuth2 bearer validation checks opaque OAuth tokens against your provider's introspection endpoint.
- Workload identity federation trades a CI job's OIDC token for a short-lived key.
- IP and route allow-lists limit where callers come from and which routes they reach.
- Virtual keys are the default way to authenticate.