Skip to main content

Authentication & Authorization

LocalAI supports two authentication modes: legacy API key authentication (simple shared keys) and a full user authentication system with roles, sessions, OAuth, and per-user usage tracking.

Legacy API Key Authentication

The simplest way to protect your LocalAI instance is with API keys. Set one or more keys via environment variable or CLI flag:

# Single key
LOCALAI_API_KEY=sk-my-secret-key localai run

# Multiple keys (comma-separated)
LOCALAI_API_KEY=key1,key2,key3 localai run

Clients provide the key via any of these methods:

  • Authorization: Bearer <key> header
  • x-api-key: <key> header
  • xi-api-key: <key> header
  • token cookie

Legacy API keys grant full admin access - there is no role separation. For multi-user deployments with role-based access, use the user authentication system instead.

API keys can also be managed at runtime through the Runtime Settings interface.

Protected and anonymous HTTP routes

When you configure database authentication or legacy API keys, LocalAI makes the HTTP surface private by default. An anonymous request succeeds only for an approved method and path or an explicit deployment override. If you configure neither authentication mode, the authentication middleware does not restrict requests.

Public discovery APIs

The following discovery requests are available anonymously:

  • GET /.well-known/localai.json
  • GET /api/instructions
  • GET /api/instructions/{name}
  • Swagger GET requests at /swagger and under /swagger/

These discovery APIs describe the server’s API surface. The endpoints that they advertise still require credentials unless this section lists them as public or bootstrap routes.

Anonymous bootstrap routes

LocalAI also permits the requests needed for health checks, credential acquisition, and the login UI. These routes do not make the rest of the API public.

  • Health checks: GET /healthz and GET /readyz.
  • Authentication status and token login: GET /api/auth/status and POST /api/auth/token-login.
  • Local registration and login: POST /api/auth/register and POST /api/auth/login.
  • Password reset: POST /api/auth/forgot-password and POST /api/auth/reset-password.
  • GitHub OAuth: GET /api/auth/github/login and GET /api/auth/github/callback.
  • OIDC: GET /api/auth/oidc/login and GET /api/auth/oidc/callback.
  • CORS preflight requests: OPTIONS on every path. A cross-origin preflight cannot carry credentials by HTTP spec, so these requests are never gated on auth; the CORS middleware answers them, which grants no API access.
  • SPA shell routes: GET /, HEAD /, and GET requests at /app, /browse, /login, /reset-password, and /invite/*. Subpaths under /app/ and /browse/ are also available through GET.
  • SPA assets: GET /favicon.svg and GET requests under /assets/, /locales/, and /static/.
  • Branding reads: GET /api/branding and GET requests under /branding/asset/. Branding mutations still require admin credentials.

Routes that require credentials

Without an explicit deployment override, every other route requires credentials. This includes GET /version, all model and backend API routes, and all inference routes. MCP and moderation aliases are also private:

  • POST /v1/mcp/chat/completions, POST /mcp/v1/chat/completions, and POST /mcp/chat/completions
  • POST /v1/moderations and POST /moderations

Generated output URLs also require credentials. This applies to every URL under /generated-audio/, /generated-images/, /generated-videos/, and /generated-3d/.

Explicit deployment overrides

Embedded deployments can add path prefixes to ApplicationConfig.PathWithoutAuth. Each prefix bypasses global authentication for every HTTP method below that prefix. Route-specific authorization still applies when the route registers it. Keep these overrides as narrow as possible; the default list is empty.

Two legacy flags provide a separate GET-only compatibility override when legacy API keys are configured:

  • LOCALAI_DISABLE_API_KEY_REQUIREMENT_FOR_HTTP_GET=true enables the override.
  • LOCALAI_HTTP_GET_EXEMPTED_ENDPOINTS sets the regular expressions for the exempt GET routes.

The endpoint expressions have no effect unless you enable LOCALAI_DISABLE_API_KEY_REQUIREMENT_FOR_HTTP_GET. Review custom expressions carefully because they can expose protected reads.

User Authentication System

The user authentication system provides:

  • User accounts with email, name, and avatar
  • Role-based access control (admin vs. user)
  • Session-based authentication with secure cookies
  • OAuth login (GitHub) and OIDC single sign-on (Keycloak, Google, Okta, Authentik, etc.)
  • Per-user API keys for programmatic access
  • Client keys for paired clients: a one-time pairing code gives a client a key that reaches only the routes of its feature list. A key can use the standard inference API for a list of models that the owner chose (client_inference), call the add-ons that the owner chose (client_addons), or both. See Paired clients: inference and add-ons
  • Admin route gating - management endpoints are restricted to admins
  • Per-user usage tracking with token consumption metrics

Enabling Authentication

Set LOCALAI_AUTH=true or provide a GitHub OAuth Client ID or OIDC Client ID (which auto-enables auth):

# Enable with SQLite (default, stored at {DataPath}/database.db)
LOCALAI_AUTH=true localai run

# Enable with GitHub OAuth
GITHUB_CLIENT_ID=your-client-id \
GITHUB_CLIENT_SECRET=your-client-secret \
LOCALAI_BASE_URL=http://localhost:8080 \
localai run

# Enable with OIDC provider (e.g. Keycloak)
LOCALAI_OIDC_ISSUER=https://keycloak.example.com/realms/myrealm \
LOCALAI_OIDC_CLIENT_ID=your-client-id \
LOCALAI_OIDC_CLIENT_SECRET=your-client-secret \
LOCALAI_BASE_URL=http://localhost:8080 \
localai run

# Enable with PostgreSQL
LOCALAI_AUTH=true \
LOCALAI_AUTH_DATABASE_URL=postgres://user:pass@host/dbname \
localai run

Enabling auth on an existing instance

Enabling user authentication does not assign existing data to an account. With authentication off, everything the chats made (chats, saved agents, triggers, connector bindings, MCP connectors, notifications and the files of the workspace) belongs to one anonymous owner, and that owner is not an account. Authenticated users, admins included, get separate storage, so the anonymous data stays in the database or on disk but no account can see it, in the API or the Web UI.

What happens to each part when you switch authentication on:

  • Chats, saved agents, notifications and files stay under the anonymous owner. No user sees them. Copy what you need into the new account first (see the steps below).
  • Triggers and connector bindings of the anonymous owner stop. The owner no longer exists as a user, so the trigger runner skips the next run and switches each trigger off with the reason “its owner no longer exists”, and a connector bot answers “not available” and is switched off.
  • Collections made without a user belong to the root storage area. With authentication on, each user has their own collections (see Collections); only the legacy owner (see below) keeps the root ones.
  • Old agents, tasks, skills, Telegram connectors and saved chats of the previous agent pool are converted at start and given to the account that owned them (see Chats migration). With authentication on, an old item that belongs to no user goes to the legacy owner (LOCALAI_AUTH_LEGACY_OWNER, see below) when one is configured and has an account; otherwise it is not converted: the report at /app/chats/conversion lists it as skipped, and you make it again under the intended account.
Warning

LocalAI does not migrate, delete or pause anything when you enable authentication. Nothing moves the anonymous data to an account.

To keep the root storage area without moving it, name the account that owns it with LOCALAI_AUTH_LEGACY_OWNER. Requests authenticated as that account (session or one of its API keys) use the root storage area instead of a per-user one, so the collections made while auth was off stay visible and usable, and switching auth off again returns to the same data. The fine-tuning and quantization job endpoints answer that account as they answer without auth, with the jobs of every user. Every other account keeps its own storage area. The account is matched by e-mail, case-insensitively, and must hold the admin role: LocalAI grants that role only to the first account, to a verified OAuth/OIDC e-mail that matches LOCALAI_ADMIN_EMAIL, or through an administrator, so an identity that merely reports the owner’s address without verification keeps its own area. Register the owner account first, or sign in with a verified OAuth/OIDC identity, before anyone else can register. Legacy API keys (LOCALAI_API_KEY) are not the owner, and an owner account that loses the admin role loses the root area with it.

The owner’s chats use the root area too: their collection tools (list_collections, search_collection) and the texts proposed for Knowledge work on the root collections. While the owner works in the root area, collections that other accounts share with the owner are not reachable. The old agent-pool items of no user are converted to the owner’s account (see the list above). The chats’ own data of the anonymous owner (chats, saved agents, triggers, connector bindings, notifications and files made with the chats while auth was off) is not part of the root storage area and is not covered: export and import it as described below.

LOCALAI_AUTH=true \
LOCALAI_ADMIN_EMAIL=owner@example.com \
LOCALAI_AUTH_LEGACY_OWNER=owner@example.com \
LOCALAI_REGISTRATION_MODE=invite \
local-ai run

Without LOCALAI_AUTH_LEGACY_OWNER, or for any other account, the steps below apply.

Before switching an existing instance:

  1. Switch off the triggers and Telegram bindings you want to keep, while auth is still off.
  2. Export what you want to keep. Export each chat as JSON (GET /api/chats/{id}/export?format=json) and each saved agent (GET /api/chats/agents/{id}/export). Recreate triggers and bindings by hand.
  3. Stop LocalAI and back up its data path and any separately configured collection storage or databases.
  4. Test the switch on a copy before changing the production instance.
  5. Restrict access during bootstrap and register the intended administrator first.
  6. Import the chats and agents under the intended user (POST /api/chats/import, POST /api/chats/agents/import). Recreate collections there as needed.
  7. Grant the new accounts the features they need. Saved agents, triggers, connectors and agent jobs are off by default for a user (see Chats permissions); an administrator has all of them.
  8. Open the conversion report and check each item, and verify credentials and required data, before resuming triggers and bots.

The first registered user becomes admin and bypasses approval or invite requirements. Setting LOCALAI_ADMIN_EMAIL promotes a matching verified OAuth/OIDC identity, but does not reserve the first-admin role for it. Local password registration cannot prove ownership of an email address and therefore never receives this automatic promotion. Keep registration inaccessible to other users until bootstrap is complete.

An export holds the transcript and the settings of a chat, and the definition of an agent. It does not hold files, trigger state, bot tokens or the long-term state of the model. Keep the backup: LocalAI has no automatic migration of the anonymous owner’s data.

A trigger or a Telegram bot acts as its owner, with the owner’s rights: the agent gets only what the owner may use at that moment, under the owner’s quota and model allowlist. It does not use an API key of its own. An administrator who switches the chats feature off for a user, or the triggers or connectors feature, also stops what that user’s triggers and bots do, at their next run or message; the trigger and the binding stay, and work again when the feature is given back.

Configuration Reference

Environment VariableDefaultDescription
LOCALAI_AUTHfalseEnable user authentication and authorization
LOCALAI_AUTH_DATABASE_URL{DataPath}/database.dbDatabase URL - postgres://... for PostgreSQL, or a file path for SQLite
GITHUB_CLIENT_IDGitHub OAuth App Client ID (auto-enables auth when set)
GITHUB_CLIENT_SECRETGitHub OAuth App Client Secret
LOCALAI_OIDC_ISSUEROIDC issuer URL for auto-discovery (e.g. https://accounts.google.com)
LOCALAI_OIDC_CLIENT_IDOIDC Client ID (auto-enables auth when set)
LOCALAI_OIDC_CLIENT_SECRETOIDC Client Secret
LOCALAI_BASE_URLBase URL for OAuth callbacks (e.g. http://localhost:8080)
LOCALAI_ADMIN_EMAILVerified OAuth/OIDC email address to auto-promote; does not reserve bootstrap admin (the first account is admin)
LOCALAI_AUTH_LEGACY_OWNEREmail address of the account that keeps the root storage area (data created while auth was off)
LOCALAI_REGISTRATION_MODEapprovalRegistration mode: open, approval, or invite
LOCALAI_DISABLE_LOCAL_AUTHfalseDisable local email/password registration and login (for OAuth/OIDC-only deployments)
LOCALAI_AUTH_LINK_VERIFIED_EMAILfalseLet a first GitHub or OIDC sign-in whose email the provider verified sign in to the local account with that email. When off, such a sign-in is refused. See One account per email
LOCALAI_SMTP_HOSTOutbound SMTP server hostname for password reset and invite emails. See Password reset and invite emails
LOCALAI_SMTP_PORT587Outbound SMTP server port
LOCALAI_SMTP_USEROutbound SMTP username (optional)
LOCALAI_SMTP_PASSWORDOutbound SMTP password (optional)
LOCALAI_SMTP_FROMSender address, e.g. LocalAI <noreply@example.com>
LOCALAI_SMTP_TLSstarttlsOutbound SMTP TLS mode: starttls, tls (implicit TLS, usually port 465), or none

Note: network-backed storage. File-based SQLite relies on POSIX file locking, which is unreliable over network filesystems (SMB/CIFS/NFS, e.g. Azure Files / Azure Container Apps shared volumes). On such storage the auth DB can fail to migrate with database is locked. Use PostgreSQL (LOCALAI_AUTH_DATABASE_URL=postgres://...) when the data directory lives on shared or network storage, or place database.db on a local volume.

SQLite storage settings

One SQLite file holds the accounts and everything else that LocalAI keeps in the auth database (the chats, their files, the triggers and the notifications). Many parts of the server write to it at the same time, so LocalAI opens it with these settings:

SettingValueWhy
Journal modeWALA reader never blocks the writer and the writer never blocks readers. In the default rollback journal, a cursor that is still open can make a commit on another connection fail with database is locked.
SynchronousNORMALThe usual pair of WAL. After a power loss the last commits can be lost, but the file stays sound.
Busy timeout10 secondsA writer waits for the one write lock instead of failing at once.
Foreign keysonThe foreign keys of the schema are enforced.
Write transactionsBEGIN IMMEDIATEA transaction that reads and then writes takes the write lock at its start, so it cannot fail halfway because another connection committed.
Connection poolat most 16 connections (1 for :memory:)SQLite has one writer, so more connections only wait.

WAL adds two files beside the database, database.db-wal and database.db-shm. Copy or back up all three together, or run PRAGMA wal_checkpoint(TRUNCATE) first.

You can change a setting in the database URL. A value that you give always wins, for example LOCALAI_AUTH_DATABASE_URL="/data/database.db?_pragma=journal_mode(DELETE)&_pragma=busy_timeout(30000)". Use journal_mode(DELETE) on a volume where WAL does not work (see the note above on network storage).

One process only. SQLite coordinates writers through file locks on one host. Run one LocalAI process per database file. Two servers on the same file, or on a file that is on a network share, are not supported: use PostgreSQL when more than one instance must share the accounts. The pool and the timeouts bound the waiting inside one process; they do not make a shared file safe.

A part of the code that holds a cursor open (rows that it reads one by one) and also writes needs a second connection for the write. Keep the cursors short, or read the rows into memory first, so the 16 connections cannot all be taken by cursors.

Disabling Local Authentication

If you want to enforce OAuth/OIDC-only login and prevent users from registering or logging in with email/password, set LOCALAI_DISABLE_LOCAL_AUTH=true (or pass --disable-local-auth):

# OAuth-only setup (no email/password)
LOCALAI_DISABLE_LOCAL_AUTH=true \
GITHUB_CLIENT_ID=your-client-id \
GITHUB_CLIENT_SECRET=your-client-secret \
LOCALAI_BASE_URL=http://localhost:8080 \
localai run

When disabled:

  • The login page will not show email/password forms (the UI checks the providers list from /api/auth/status)
  • POST /api/auth/register returns 403 Forbidden
  • POST /api/auth/login returns 403 Forbidden
  • OAuth/OIDC login continues to work normally

One account per email

An account is identified by its sign-in method: a local account by its email, a GitHub or OIDC account by the provider and the user ID the provider gives. So the same email could become two accounts, for example a local admin account made before OIDC was configured, and an OIDC account made on the first OIDC sign-in. Each has its own API keys, usage, permissions and data.

To prevent this, when local sign-in is enabled, the first GitHub or OIDC sign-in with the email of a local account is refused. The login page says that an account with this email exists, and the person signs in with the password.

If you trust the provider to verify emails, set LOCALAI_AUTH_LINK_VERIFIED_EMAIL=true (or pass --link-verified-email). A first sign-in whose email the provider verified (email_verified in the OIDC ID token; GitHub’s primary email) then signs in to the local account. The local account does not change: its role, its password sign-in and its data stay. A sign-in with an unverified email is still refused.

With LOCALAI_DISABLE_LOCAL_AUTH=true, the local account cannot be used, so the check does not apply and the sign-in gets its own account, as before.

Two accounts that already exist for one email are not merged.

Roles

There are two roles:

  • Admin: Full access to all endpoints, including model management, backend configuration, system settings, traces, the saved agents, triggers and connectors of every user (read-only, with switch-off and delete), and user management.
  • User: Access to inference endpoints only - chat completions, embeddings, image/video/audio generation, TTS, MCP chat, and their own usage statistics.

The first user to sign in is automatically assigned the admin role. Additional users can be promoted through the admin user management API. A verified OAuth/OIDC identity can also be promoted by setting LOCALAI_ADMIN_EMAIL to its email address; local password accounts are not eligible because their email ownership is not verified.

Feature defaults

Each feature has a default: the value a user gets when their permissions do not name the feature. Most defaults are fixed. API features such as chat and images are on, and agent and general features such as saved agents and add-ons are off.

An administrator can change the default of a feature that is marked configurable. Today only Pair own devices (P2P) (p2p_pair) is configurable. Its built-in default is off.

# See every feature, the default in force and whether it is configurable
curl http://localhost:8080/api/auth/admin/features \
  -H "Authorization: Bearer <admin-key>"

# Turn the default of p2p_pair on for every user
curl -X PUT http://localhost:8080/api/auth/admin/features/p2p_pair/default \
  -H "Authorization: Bearer <admin-key>" \
  -H "Content-Type: application/json" \
  -d '{"enabled": true}'

A user who has p2p_pair may pair their own phone over P2P; the phone then signs in as that user. See Users pair their own phones. Disabling or deleting a user revokes the phones that sign in as that user and ends their sessions. The session of a phone works only over P2P from that phone: the normal HTTP listener refuses it.

In the response of GET /api/auth/admin/features, default is the default in force and configurable tells whether the PUT accepts the feature. The PUT answers 400 for a feature that is not configurable and 404 for an unknown feature.

In the web UI, open Users, then the access sheet of a user. Under Add-ons and Models, choose All or Only these, then add entries with the picker. Each entry shows as a chip that you can remove. A pick that is not installed says so. The add-on choice needs the Add-ons feature to be on for that user. If a save returns a warning, the sheet stays open and shows it.

These rules apply:

  • A value in a user’s permissions wins over the default. If you turned a feature off for one user, that user stays without it when you turn the default on.
  • Administrators always have every feature.
  • The default is stored in the auth database (table feature_defaults, with the time of the change and the administrator who made it), so it survives a restart. Each frontend keeps a copy for up to 30 seconds. The frontend that took the change applies it at once; in distributed mode the other frontends apply it within 30 seconds.

Follow the default or set a value

For each feature, a user either follows the default or has an explicit value:

  • Follows the default: the user’s permissions do not name the feature. When you change the default, the user gets the new value.
  • Explicit value: the user’s permissions name the feature with true or false. A change of the default does not apply to this user.

In the web UI, open Users, then the access sheet of a user. Under each configurable feature the sheet shows which of the two applies. Use default removes the explicit value, and the user follows the default again. When you save the sheet, it keeps the explicit values the user already had and adds only the features you changed. The other features keep following the default.

The API shows both maps. GET /api/auth/admin/users and GET /api/auth/admin/users/{id}/permissions return permissions, the effective value of every feature, and explicit_permissions, only the features the user has an explicit value for. PUT /api/auth/admin/users/{id}/permissions replaces the explicit map. To make a user follow the default of a feature, send the map without that feature, or with the feature set to null:

# Keep mcp on for this user; p2p_pair follows the default
curl -X PUT http://localhost:8080/api/auth/admin/users/<user-id>/permissions \
  -H "Authorization: Bearer <admin-key>" \
  -H "Content-Type: application/json" \
  -d '{"mcp": true, "p2p_pair": null}'

Read explicit_permissions first and send it back with your changes: a key you leave out follows the default.

Add-on access

An administrator chooses, for each user, which add-ons that user may use. There are two modes:

ModeValueResult
All add-ons (default){"enabled": false}The user may use every add-on, also the ones you install later.
Only these{"enabled": true, "addons": ["..."]}The user may use only the listed add-ons. An empty list means no add-on.
curl -X PUT http://localhost:8080/api/auth/admin/users/<user-id>/addons \
  -H "Authorization: Bearer <admin-key>" \
  -H "Content-Type: application/json" \
  -d '{"enabled": true, "addons": ["sample"]}'

The request replaces the whole setting. enabled is required: a body without it answers 400. With enabled false, LocalAI stores no add-on IDs. A malformed add-on ID answers 400 and an unknown user answers 404. Duplicate IDs are dropped. An ID of an add-on that is not installed is kept.

When a change takes add-ons away from a user, LocalAI also takes them away at once. This includes a move from All add-ons to Only these, which takes away every installed add-on that the list does not name. LocalAI stops the work that the user runs on those add-ons now. A background job that the user started on them loses its lease: from then on the host refuses its host operations, such as its final checkpoint. It also switches off every connection of the user that those add-ons serve, also a connection that the user shares with other people, and tells the user in the Inbox. While the user may not use an add-on, the people the user shares a connection of it with cannot use that connection either: it answers as a connection that does not exist, or as unavailable when LocalAI cannot read the setting. The connections stay off when you give the add-ons back: the user switches them on again. If LocalAI cannot do all of this, the answer is still 200 and has a warning that says what did not finish. The saved setting stays, and LocalAI refuses the removed add-ons from the next call. An administrator keeps every add-on, so a change to an administrator’s list stops nothing. In a distributed setup the frontend that saves the change reads the installed add-ons from the add-on owner and asks the owner to stop the work.

The add-on owner stops the work only for a named administrator. A save with the legacy API key (LOCALAI_API_KEY) is not a named user, so the owner does not stop the running work, and in a distributed setup the user’s connections may stay on. The setting is saved, and the answer is 200 with a warning that says what did not finish. The removed add-ons are still refused from the next call. To stop the running work at once, save the change again as a named administrator.

GET /api/auth/admin/users returns the setting of each user as allowed_addons. GET /api/auth/admin/features returns the installed add-ons as addons, each with id, title and description. In a distributed setup a frontend reads this list from the add-on owner, as the administrator who asks. The owner does not answer the legacy API key, so on a frontend a request with that key gets addons_unavailable. When it cannot read the installed add-ons, addons is empty and addons_unavailable is true. The LocalAI Assistant has the same operations as the tools list_user_addons and set_user_addons.

These rules apply:

  • The addons feature stays the first gate. A user without it uses no add-on, whatever the list says. This includes connectors and watches: a user who has the connectors feature but not the addons feature sees no connector kind of an add-on and cannot create a connection of one. The connections of add-ons that such a user already has show as inactive, with the reason that the account may not use add-ons and must ask an administrator.
  • Administrators always have every add-on. A server without authentication has one local owner, who has every add-on too.
  • Users who existed before this setting are in the All add-ons mode.
  • Upgrade note: the connectors that add-ons serve now need the addons feature too, not only the connectors feature. After the upgrade, a user who has connectors but not addons cannot use, create or switch on a connection of an add-on, and the existing ones show as inactive. Give such users the addons feature if they must keep their connections.
  • The apps list leaves out an add-on that the user may not use. Its files, icons, update status, pins and per-user settings answer as for an add-on that does not exist. If LocalAI cannot read the setting, these requests fail as unavailable.
  • Calls to an add-on that the user may not use (tool calls, actions, its resources and proposed changes) are refused as for an add-on that does not exist. LocalAI reads the setting again on each call, so a change applies to the next call. In a distributed setup the add-on owner makes this check for every frontend.
  • Pending proposals of an add-on that the user may not use are left out of the pending list, and cannot be read, looked up, confirmed again, cancelled or resolved: each request answers as for an unknown proposal. A pending proposal stays stored until it expires. A refused user’s creation with an unknown outcome counts against their limits until access returns or the next start settles it. The same applies to the file results of the add-on: their status and download answer as for an unknown result. If LocalAI cannot read the setting, these requests fail as unavailable.
  • Chat connectors follow the same list. The user’s list of connector kinds leaves out the add-on, and its connections show as if it was not installed. LocalAI refuses to create, change or switch on such a connection, receives no message for it and sends none through it. You can still switch it off or delete it. If LocalAI cannot read the setting, it answers as unavailable and does not switch any connection off.
  • Add-on logins (OAuth) follow the same list. For an add-on that the user may not use, LocalAI refuses to start or finish a login, and it does not use or renew the stored token. You can still disconnect the login or delete the connection. The routes and host operations of paired clients check the list of the client owner too; an owner of a client is an administrator, who has every add-on.
  • Watches follow the same list. The sources of a watch leave out the add-on, and LocalAI refuses to create, change, confirm or switch on a watch of it as for an add-on that is not installed. LocalAI drops the add-on’s events for that user, and an existing watch and its reminders start no run. The watch is not switched off or deleted; you can still do that yourself. A connection of the add-on cannot receive the report of a trigger. If LocalAI cannot read the setting, these requests fail as unavailable and a run that is due fails. LocalAI does not retry a run that was due while it could not check the permissions.
  • Automations follow the same list. The automation catalog leaves out the add-on: its events, its tools and its setup choices. A describe of one of its events answers as for an add-on that is not installed. A step cannot call its tools, and the start of an automation that names one of its events gives only the fields that the user set. LocalAI does not ask the add-on for new events of the user, drops the events that it reports for the user, and does not deliver the user’s events to it when it subscribes. LocalAI asks again before each attempt of a delivery. If LocalAI cannot read the setting, the catalog and the describe fail as unavailable, a poll waits and is tried again, an event is not taken, and a delivery is tried again later.
  • The skills of an add-on that the user may not use are hidden as if the add-on was not installed: in the skills API (GET /api/chats/skills/addon/{name}?addon=...), and in /workspace/shared-addon-skills for the file tools and the commands of every chat. A running command sandbox gets the new list at its next command. If LocalAI cannot read the setting, the skills API answers 503 and the chats see no add-on skills.
  • Sharing follows the same list. The user search of an add-on resource’s share dialog leaves out the people who may not use the add-on. An owner who already knows the ID of such a person can still create a grant, but every use by that person is refused. A share that a person already has stays: the Add-ons page tells that person who shared how many items in which installed add-on, and to ask an administrator. GET /api/addons/apps has this as blockedShares (addonId, title, titles, count, owners as display names). It names no resource. The searches of the kinds that are not add-ons (/api/shares, folders) do not use this list.

Registration Modes

ModeDescription
openAnyone can register and is immediately active
approvalNew users land in “pending” status until an admin approves them. If a valid invite code is provided during registration, the user is activated immediately (skipping the approval wait). (default)
inviteRegistration requires a valid invite link generated by an admin. Without one, registration is rejected.

Last activity and API key count

The Users page shows, for each person, when they were last active and how many API keys they hold. Only administrators can read them: GET /api/auth/admin/users returns lastActiveAt (a time, or null when no activity was recorded) and apiKeyCount (a number) for each user, and no other endpoint returns them.

LocalAI records one thing: the time of the last authenticated request of the person, made with a session or with one of their API keys. It writes at most once every five minutes for a person, so a busy client does not cause a write for each request. It stores no address, no user agent and no path. The key count is a number; it never carries the keys or their names, and LocalAI still lists a person’s keys only to that person. A paired client key is not counted, and its requests do not set the time. The Users page has an Inactive 30 d+ filter for people who were not active for 30 days or more.

View as another user

An administrator can open the web UI as another person, read-only first. See View as another user.

Admins can generate single-use, time-limited invite links from Administration → Access → Users → Invite someone in the web UI (choose 1, 7 or 30 days), or via the API:

# Create an invite link (default: expires in 7 days)
curl -X POST http://localhost:8080/api/auth/admin/invites \
  -H "Authorization: Bearer <admin-key>" \
  -H "Content-Type: application/json" \
  -d '{"expiresInHours": 168}'

# List all invites
curl http://localhost:8080/api/auth/admin/invites \
  -H "Authorization: Bearer <admin-key>"

# Revoke an unused invite
curl -X DELETE http://localhost:8080/api/auth/admin/invites/<invite-id> \
  -H "Authorization: Bearer <admin-key>"

An invite records the account that created it. A legacy LOCALAI_API_KEY has no account, so the invites it creates have no creator (see below).

Share the invite URL (/invite/<code>) with the user. The link is shown once, when you create it: the invite list keeps only the first characters of the code, so a link you did not copy can only be revoked and made again. When the user opens it, the registration form is pre-filled with the invite code. LocalAI validates the code only when the user submits registration. Invite codes are single-use - once consumed, they cannot be reused. Expired or used invites are rejected.

The <admin-key> can be an admin user’s API key or a legacy API key (LOCALAI_API_KEY). A legacy API key belongs to no user account, so the invites it creates are listed with createdBy: null.

For GitHub OAuth, the invite code is passed as a query parameter to the login URL (/api/auth/github/login?invite_code=<code>) and stored in a cookie during the OAuth flow.

Admin-Only Endpoints

When authentication is enabled, the following endpoints require admin role:

Model & Backend Management:

  • GET /api/models, POST /api/models/install/*, POST /api/models/delete/*
  • GET /api/backends, POST /api/backends/install/*, POST /api/backends/delete/*
  • GET /api/operations, POST /api/operations/*/cancel, POST /api/operations/*/pause, POST /api/operations/*/dismiss
  • GET /api/operations/history, DELETE /api/operations/history
  • GET /models/available, GET /models/galleries, GET /models/jobs/*
  • GET /backends, GET /backends/available, GET /backends/galleries

System & Monitoring:

  • GET /api/traces, GET /api/traces/summary, GET /api/traces/{id}, POST /api/traces/clear
  • GET /api/backend-traces, GET /api/backend-traces/{id}, POST /api/backend-traces/clear
  • GET /api/backend-logs/*, POST /api/backend-logs/*/clear
  • GET /api/resources, GET /api/settings, POST /api/settings
  • GET /system, GET /backend/monitor, POST /backend/shutdown, POST /backend/load
  • POST /v1/slots/save, POST /v1/slots/restore (write and read prompt-cache files on the host)

P2P:

  • GET /api/p2p/*

User-Accessible Endpoints (all authenticated users):

  • POST /v1/chat/completions, POST /v1/embeddings, POST /v1/completions
  • POST /v1/images/generations, POST /v1/audio/*, POST /tts, POST /vad, POST /video
  • GET /v1/models, POST /v1/tokenize, POST /v1/detokenize, POST /v1/detection
  • POST /v1/mcp/chat/completions, POST /v1/messages, POST /v1/responses
  • POST /stores/*, GET /api/cors-proxy
  • GET /version, GET /api/features, GET /metrics
  • GET /api/auth/usage (own usage data)

Web UI Access Control

When auth is enabled, the React UI sidebar dynamically shows/hides sections based on the user’s role:

  • All users see: Home, Chat, Images, Video, TTS, Sound, Talk, Usage, API docs link
  • Admins also see: Models, the Build console (Training, Recognition and the other tools that need an administrator), and the Admin section (Backends, Activity, Workers, Traffic, Settings, Users and API keys)

Admin-only pages are also protected at the router level - navigating directly to an admin URL redirects non-admin users to the home page.

On Home, the machine widget with the list of loaded models is shown to admins only, because it reads the admin endpoints GET /system and GET /api/resources. Other users do not see the widget, rather than a “No models loaded” that may not be true.

In Chat, a non-admin user holding the mcp feature can select the MCP servers of a model whose configuration declares them (MCP → Servers, plus that model’s MCP prompts and resources). Users without the mcp feature only see client-side MCP. The model information panel and the automatic context size stay admin-only, because they read the full model configuration.

Sign-in, invite and account pages

The sign-in screen offers only what GET /api/auth/status reports:

  • A GitHub or SSO button appears only when that provider is configured. With LOCALAI_DISABLE_LOCAL_AUTH=true there is no email form.
  • Email and password sign-in asks for one field at a time: the email, then the password. Both are sent in one call, so the server still never says whether an email exists.
  • Registration asks for the email, then the name, password and (when the registration mode allows one) an invite code. A sign-up that waits for approval returns to the sign-in screen with a notice that an admin must approve it.
  • On a server with no users yet, the first screen is “Create the admin account”.
  • On a server protected only by legacy API keys, the screen asks for the key and nothing else.
  • An invite link (/invite/<code>) opens registration with the code filled in and read-only.

The Account page has four tabs: Profile (name and picture address), Security (change a local password; for a GitHub or SSO account it says the password is managed by the provider), API keys, and Usage (your requests, tokens by model, and the limits an admin set on you, for the last 30 days). Administration → Access → Users has the people and the invites, and Administration → Access → API keys has your own API keys.

GitHub OAuth Setup

  1. Create a GitHub OAuth App at Settings → Developer settings → OAuth Apps → New OAuth App
  2. Set the Authorization callback URL to {LOCALAI_BASE_URL}/api/auth/github/callback
  3. Set GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET environment variables
  4. Set LOCALAI_BASE_URL to your publicly-accessible URL

OIDC Setup

Any OIDC-compliant identity provider can be used for single sign-on. This includes Keycloak, Google, Okta, Authentik, Azure AD, and many others.

Steps:

  1. Create a client/application in your OIDC provider
  2. Set the redirect URL to {LOCALAI_BASE_URL}/api/auth/oidc/callback
  3. Set the three environment variables: LOCALAI_OIDC_ISSUER, LOCALAI_OIDC_CLIENT_ID, LOCALAI_OIDC_CLIENT_SECRET

LocalAI uses OIDC auto-discovery (the /.well-known/openid-configuration endpoint) and requests the standard scopes: openid, profile, email.

Provider examples:

# Keycloak
LOCALAI_OIDC_ISSUER=https://keycloak.example.com/realms/myrealm

# Google
LOCALAI_OIDC_ISSUER=https://accounts.google.com

# Authentik
LOCALAI_OIDC_ISSUER=https://authentik.example.com/application/o/localai/

# Okta
LOCALAI_OIDC_ISSUER=https://your-org.okta.com

For OIDC, invite codes work the same way as GitHub OAuth - the invite code is passed as a query parameter to the login URL (/api/auth/oidc/login?invite_code=<code>) and stored in a cookie during the OAuth flow.

User API Keys

Authenticated users can create personal API keys for programmatic access:

# Create an API key (requires session auth)
curl -X POST http://localhost:8080/api/auth/api-keys \
  -H "Cookie: session=<session-id>" \
  -H "Content-Type: application/json" \
  -d '{"name": "My Script Key"}'

User API keys inherit the creating user’s role. Admin keys grant admin access; user keys grant user-level access.

You can pause a key without deleting it, and resume it later. Only the key’s owner can pause it. A paused key is rejected like an invalid key until it is resumed. Pause it until you resume it, or until a time in the future, after which it works again by itself:

# Pause until resumed
curl -X PATCH http://localhost:8080/api/auth/api-keys/<key-id> \
  -H "Cookie: session=<session-id>" \
  -H "Content-Type: application/json" \
  -d '{"disabled": true, "paused_until": null}'

# Pause until a given time (RFC 3339, must be in the future)
curl -X PATCH http://localhost:8080/api/auth/api-keys/<key-id> \
  -H "Cookie: session=<session-id>" \
  -H "Content-Type: application/json" \
  -d '{"disabled": false, "paused_until": "2030-01-01T00:00:00Z"}'

# Resume
curl -X PATCH http://localhost:8080/api/auth/api-keys/<key-id> \
  -H "Cookie: session=<session-id>" \
  -H "Content-Type: application/json" \
  -d '{"disabled": false, "paused_until": null}'

The key list returns disabled and, when set, pausedUntil for each key. The Account page in the web UI has a Pause and Resume button for each key.

A key can be created with a lifetime: send expiresIn (30d, 90d or 1y) or expiresAt (RFC 3339). Without either, the server applies LOCALAI_DEFAULT_API_KEY_EXPIRY when it is set, and the key does not expire otherwise. The full key is returned once, in the response to the create call; the list returns only its prefix, the creation time, lastUsed and expiresAt.

In the web UI, the API keys tab of the Account page and Administration → Access → API keys show the signed-in person’s own keys: a new key is shown once with a Copy button, and the lifetime list sends expiresIn. Revoking a key waits ten seconds in the browser before it sends the DELETE, and Undo inside that time sends nothing; leaving the page sends a revoke that is still waiting. LocalAI lists a person’s keys only to that person, so an admin cannot list or revoke other users’ keys, in the UI or through the API. The Usage page can group requests by API key for everyone.

Auth API Endpoints

MethodEndpointDescriptionAuth Required
GET/api/auth/statusAuth state, current user, providersNo
POST/api/auth/token-loginExchange a user or legacy API key for a browser sessionNo
POST/api/auth/registerRegister with email and passwordNo
POST/api/auth/loginLog in with email and passwordNo
POST/api/auth/forgot-passwordEmail a password reset link to a local accountNo
POST/api/auth/reset-passwordSet a new password with the token from the reset linkNo
GET/api/auth/github/loginStart GitHub OAuthNo
GET/api/auth/github/callbackGitHub OAuth callback (internal)No
GET/api/auth/oidc/loginStart OIDC loginNo
GET/api/auth/oidc/callbackOIDC callback (internal)No
POST/api/auth/logoutEnd sessionYes
GET/api/auth/meCurrent user infoYes
POST/api/auth/api-keysCreate API keyYes
GET/api/auth/api-keysList user’s API keysYes
PATCH/api/auth/api-keys/:idPause or resume API keyYes
DELETE/api/auth/api-keys/:idRevoke API keyYes
GET/api/auth/usageUser’s own usage statsYes
GET/api/auth/usage/sourcesUser’s own per-API-key / per-source breakdownYes
GET/api/auth/admin/featuresList the features, the default in force and whether it is configurableAdmin
PUT/api/auth/admin/features/:feature/defaultChange the default of a configurable feature ({"enabled": bool})Admin
GET/api/auth/admin/usersList all users, with lastActiveAt and apiKeyCountAdmin
PUT/api/auth/admin/users/:id/roleChange user roleAdmin
DELETE/api/auth/admin/users/:idDelete userAdmin
PUT/api/auth/admin/users/:id/addonsChoose the add-ons a user may use ({"enabled": bool, "addons": [...]})Admin
GET/api/auth/admin/usageAll users’ usage statsAdmin
GET/api/auth/admin/usage/sourcesAll users’ per-API-key / per-source breakdownAdmin
POST/api/auth/admin/invitesCreate invite linkAdmin
GET/api/auth/admin/invitesList all invitesAdmin
DELETE/api/auth/admin/invites/:idRevoke unused inviteAdmin
POST/api/auth/admin/smtp/testSend a test email ({"to": "..."}, default: your own email)Admin

Usage Tracking

When authentication is enabled, LocalAI automatically tracks per-user token usage for inference endpoints. Usage data includes:

  • Prompt tokens, completion tokens, and total tokens per request
  • Model used and endpoint called
  • Request duration
  • Timestamp for time-series aggregation

Viewing Usage

Usage is accessible through the Usage page in the web UI (visible to all authenticated users) or via the API:

# Get your own usage (default: last 30 days)
curl http://localhost:8080/api/auth/usage?period=month \
  -H "Authorization: Bearer <key>"

# Admin: get all users' usage
curl http://localhost:8080/api/auth/admin/usage?period=week \
  -H "Authorization: Bearer <admin-key>"

# Admin: filter by specific user
curl "http://localhost:8080/api/auth/admin/usage?period=month&user_id=<user-id>" \
  -H "Authorization: Bearer <admin-key>"

Period values:

  • day - last 24 hours, bucketed by hour
  • week - last 7 days, bucketed by day
  • month - last 30 days, bucketed by day (default)
  • all - all time, bucketed by month

Response format:

{
  "usage": [
    {
      "bucket": "2026-03-18",
      "model": "gpt-4",
      "user_id": "abc-123",
      "user_name": "Alice",
      "prompt_tokens": 1500,
      "completion_tokens": 800,
      "total_tokens": 2300,
      "request_count": 12
    }
  ],
  "totals": {
    "prompt_tokens": 1500,
    "completion_tokens": 800,
    "total_tokens": 2300,
    "request_count": 12
  }
}

Usage Dashboard

The web UI Usage page provides:

  • Period selector - switch between day, week, month, and all-time views
  • Summary cards - total requests, prompt tokens, completion tokens, total tokens
  • By Model table - per-model breakdown with visual usage bars
  • By User table (admin only) - per-user breakdown across all models
  • Sources tab - per-API-key and per-source breakdown (described below)

Per-API-key Breakdown

The Sources tab on the Usage page surfaces a third dimension of the same data: traffic broken down by API key and by request source. Three source classes are tracked:

  • API key - request authenticated with a named user API key (Authorization: Bearer lai-..., x-api-key, or token cookie). Each key shows up with its label (snapshotted at write time, so revoked keys still display the original name).
  • Web UI - request authenticated with a browser session cookie.
  • Legacy - request authenticated with an env-configured LOCALAI_API_KEY. Visible to admins only.

The Sources tab is visible to every authenticated user. Non-admins see only their own keys plus their own Web UI traffic (legacy is filtered server-side). Admins see every key from every user.

The tab is laid out as:

  • A source mix ribbon showing the percentage split across the three classes.
  • A top-N + Other stacked time chart (top 7 sources by total tokens; the rest roll up).
  • A searchable, sortable table of every key plus the Web UI and Legacy pseudo-rows. Click a row to filter the chart to that source.

Endpoints

MethodPathAuthDescription
GET/api/auth/usage/sourcesSelfCaller’s per-source breakdown. Excludes legacy.
GET/api/auth/admin/usage/sourcesAdminAll users’ per-source breakdown. Accepts user_id and api_key_id filters. Includes legacy.

Both endpoints accept the same period parameter (day, week, month, all) as /api/auth/usage.

# Your own per-source usage for the last week
curl "http://localhost:8080/api/auth/usage/sources?period=week" \
  -H "Authorization: Bearer <key>"

# Admin: filter to a single API key across all users
curl "http://localhost:8080/api/auth/admin/usage/sources?period=month&api_key_id=<key-id>" \
  -H "Authorization: Bearer <admin-key>"

Response shape:

{
  "buckets": [
    { "bucket": "2026-05-19", "source": "apikey",
      "api_key_id": "uuid", "api_key_name": "ci-runner",
      "total_tokens": 20000, "request_count": 142, "...": "..." },
    { "bucket": "2026-05-19", "source": "web",
      "total_tokens": 300, "request_count": 11, "...": "..." }
  ],
  "totals": {
    "by_source": {
      "apikey": { "tokens": 1234567, "requests": 8420 },
      "web":    { "tokens":   92000, "requests":   211 }
    },
    "by_key": [
      { "api_key_id": "uuid", "api_key_name": "ci-runner",
        "tokens": 2100000, "requests": 8420,
        "last_used": "2026-05-20T12:34:56Z" }
    ],
    "grand_total": { "tokens": 1334777, "requests": 8645 }
  },
  "truncated": false
}

The by_key list is server-sorted by tokens descending and capped at 200 entries. When more keys would qualify, the response sets "truncated": true so the UI can show a notice.

Migration of pre-feature data

Usage rows recorded before this feature have no source column. On startup, InitDB backfills them as legacy when the synthetic legacy-api-key user_id was used, and web for everything else. The migration is idempotent; existing aggregations remain correct after the upgrade.

Combining Auth Modes

Legacy API keys and user authentication can be used simultaneously. When both are configured:

  1. User sessions and user API keys are checked first
  2. Legacy API keys are checked as fallback - they grant admin-level access
  3. This allows a gradual migration from shared API keys to per-user accounts

Build Requirements

User authentication needs no build tag and no C compiler. The SQLite database is opened with a pure-Go driver, so a binary built with CGO_ENABLED=0 and no tags (the release binaries) can keep accounts in a SQLite file, and the same driver serves the chats and their files. PostgreSQL is chosen by the postgres:// form of the database URL, as before.

go build ./cmd/local-ai

The auth build tag is only left on some tests. The pure-Go driver reads and writes the file format of SQLite, so an existing database.db opens as it is.

Password reset and invite emails

LocalAI can send email through an SMTP server for two things: password reset links for local accounts, and invite links. Set the SMTP server and the external base URL of the instance:

LOCALAI_AUTH=true \
LOCALAI_BASE_URL=https://localai.example.com \
LOCALAI_SMTP_HOST=smtp.example.com \
LOCALAI_SMTP_PORT=587 \
LOCALAI_SMTP_USER=localai@example.com \
LOCALAI_SMTP_PASSWORD=<password> \
LOCALAI_SMTP_FROM="LocalAI <noreply@example.com>" \
local-ai run
Environment VariableCLI FlagDefaultDescription
LOCALAI_SMTP_HOST--smtp-hostSMTP server hostname
LOCALAI_SMTP_PORT--smtp-port587SMTP server port
LOCALAI_SMTP_USER--smtp-userSMTP username. Leave it empty for a server without authentication
LOCALAI_SMTP_PASSWORD--smtp-passwordSMTP password
LOCALAI_SMTP_FROM--smtp-fromSender address
LOCALAI_SMTP_TLS--smtp-tlsstarttlsstarttls, tls (implicit TLS, usually port 465), or none
LOCALAI_BASE_URL--external-base-urlExternal base URL. The links in the emails start with it

The links in the emails are built only from LOCALAI_BASE_URL, never from the Host or X-Forwarded-* headers of the request: these headers come from the client, and a link built from them could send a reset token to another host. When SMTP is set but LOCALAI_BASE_URL is not, LocalAI logs a warning at startup and sends no emails.

When email is available, GET /api/auth/status returns "smtpEnabled": true and the sign-in page shows a Forgot password? link on the password step.

Password reset. POST /api/auth/forgot-password with {"email": "..."} sends a link to /reset-password?token=... to the active local account with that email. The link is valid for one hour and works once. A new request makes the earlier links of the account invalid. The answer is the same, and comes back as fast, whether or not the account exists: LocalAI sends the email in the background, so a failed delivery shows only in the server log. POST /api/auth/reset-password with {"token": "...", "password": "..."} sets the new password and signs the account out of all its sessions. Accounts that sign in with GitHub or OIDC cannot reset a password here.

Invites. Add "email" to the body of POST /api/auth/admin/invites to send the invite link to that address. The answer has "emailSent": true when the email went out. The invite is created even when the email fails, and the answer still holds the code.

Test. POST /api/auth/admin/smtp/test sends a test email to the to address in the body, or to your own email. It answers 502 with the SMTP error when the delivery fails.

The server log does not contain the recipient addresses.