When people say "configure Dify's API key," they often mean completely different things: sometimes the provider secret that lets Dify call models, sometimes the access key that lets a business system call a Dify app, and sometimes a knowledge-base Service API key. The three are created in different places, have different permission scopes, and differ in impact when leaked. The most common consequence of mixing them up is a provider key written into a front end, an app key with too much scope handed to a caller, or a rotation aimed at the wrong object that takes production down with 401s.
Interface names and permission details may change between versions; follow the current UI and documentation of your instance.
Note: Dify is a trademark of LangGenius, Inc. This is an independent technical note with no affiliation or agency relationship with the Dify team.
1. Tell the three keys apart first
Start with a table that draws the boundaries.
| Key type | Purpose | Where to create it | Permission scope | Who can manage it |
|---|---|---|---|---|
| Model provider key | Dify calls upstream models | Settings → Model Providers → the relevant provider | Shared across the workspace | Owner, Admin |
| App API key | External systems call a Dify app | App → API Access | Single app, covering all of that app's end users | Editor and above |
| Knowledge-base Service key | External systems call the knowledge-base API | Knowledge base → Service API | Can be limited to selected knowledge bases | Editor and above |
They are not interchangeable: a provider key cannot call app endpoints, and an app key cannot make Dify call models. Before troubleshooting, confirm which kind you are holding.
2. Model provider key: workspace-level, configured by administrators
A model provider key is a workspace-level configuration, added in model provider settings and used by Dify to make model requests upstream. The platform validates it on entry and makes it available to the whole workspace once it passes. Only the owner and administrators can manage these keys; editors and normal members cannot see the settings.
A few details that are easy to overlook:
- One provider can hold several keys, split by development, production, or account, which makes billing attribution and individual suspension easier.
- Keys for custom models are managed separately. Deleting the last key also deletes the custom model; deleting only the model keeps the key, so you do not have to re-enter it when adding the model again.
- Professional and Team plans support load balancing across multiple keys for the same model. When a key hits its limit, the platform skips it for about a minute.
- When Cloud includes AI credits, you can leave the provider without a key, or run both and use Usage Priority to decide which one is used first. With your own key, costs land on your own provider account.
Name keys by purpose, environment, and owner; most provider consoles show usage per key, which helps when something looks wrong.
3. App API key: backend only
An app API key solves a different problem: how an external system calls an app that is already published. It plays no part in model selection and cannot be used to call model endpoints. The typical flow is:
- Open the target app and go to its API Access page.
- Create a key and name it by caller, environment, and date.
- Copy it into a server-side environment variable or secrets manager; never put it in a front end, a repository, or a chat log.
- Call
GET /infofirst to confirm the key matches the app. - Then call the endpoint for the app type; each type has different endpoints.
- After launch, record which app the key belongs to, who owns it, and when it was created.
# Base URL for Dify Cloud; replace it with your instance address when self-hosting
export DIFY_BASE_URL="https://api.dify.ai/v1"
export DIFY_APP_KEY="your-app-key"
curl "$DIFY_BASE_URL/info" \
-H "Authorization: Bearer $DIFY_APP_KEY"
A response with the app name, mode, and description means the key is valid. Two cautions: one app key applies to every end user of that app, and the user field in the request body only distinguishes users rather than authenticating them; and app endpoints should be called from a backend, since the documentation explicitly advises against putting keys in front-end or client code.
4. Knowledge-base Service key: limit scope whenever you can
A knowledge base has its own Service API key, created on its Service API page and separate from app keys. At creation you can limit which knowledge bases the key can access; a key with access to all knowledge bases can also call the endpoint that lists them.
The least-privilege approach is one key per consumer, with only the needed knowledge bases checked, rather than one full-access key serving everyone. A leaked knowledge-base key means data may be read or written, not just model quota consumed, so the risk is higher.
5. Where secrets live: .env, SECRET_KEY, and workspace encryption
A self-hosted deployment has two layers of secrets, and many teams change only the first.
The first layer is docker/.env, copied from .env.example; configuration at the root overrides same-named entries in docker/envs/*.env. SECRET_KEY is the one most often overlooked: it participates in session cookie and JWT signing, HMAC-SHA256 signing of file URLs, and AES-256 encryption of third-party OAuth credentials. The sample value must be replaced; you can generate one with openssl rand -base64 42.
Changing SECRET_KEY signs out every user, invalidates issued file URLs, and makes OAuth credentials encrypted with the old value unrecoverable. It is not a routine rotation item; assess the impact and take a backup before changing it.
The second layer is workspace credential encryption. Model provider keys, tool credentials, and similar items are encrypted with a per-workspace RSA key, and the private key is stored in the backend selected by STORAGE_TYPE. KEY_PROVIDER_TYPE defaults to local and can also connect to Azure Key Vault with automatic rotation. This choice must be made before the first workspace is created: ciphertexts from the two approaches are incompatible, and switching midway leaves existing credentials undecryptable, so they must be re-entered.
Newer versions also have DIFY_AGENT_SERVER_SECRET_KEY and DIFY_AGENT_API_TOKEN in agent configuration; the development defaults are public and must be replaced before going live. Do not commit .env, tighten file permissions as the documentation describes, and include key material in backups; otherwise restored environments may lose all credentials.
On Cloud, provider credentials are hosted by the platform, so you do not manage SECRET_KEY yourself, but you should still use dedicated accounts or project keys and keep records on the provider side.
6. Rotation, least privilege, and team roles
Rotation is not only for leaks. Check on staff departures, caller changes, suspected exposure, provider requirements, and a regular schedule. The full process is:
- Create a new key with the same permissions at the provider or in Dify, and run it alongside the old one.
- Write the new key into the secrets manager or environment variables and release the configuration.
- Watch error rates, call volume, and provider bills for a while to confirm traffic has moved.
- Disable the old key rather than merely deleting it from configuration.
- Record the rotation date, operator, and impact, and update handover documents.
On team roles, workspace roles are roughly: the owner holds full control and there is only one; administrators manage members and model providers; editors can create, edit, and delete apps and knowledge bases; normal members can only use published apps. A simple rule works well: provider keys stay with the owner and administrators; app keys go to the relevant backend owner; knowledge-base keys are split by consumer and scoped. Editors can modify apps and usually can reach that app's API keys, so "can edit an app" should not be treated as "can manage the company's model secrets."
7. Common errors and troubleshooting
Start by confirming the key type, then look at network and permissions.
- 401 authentication error: the key is mistyped, revoked, has stray spaces or newlines, or a provider key was used as an app key. Retest with
GET /info. - 403 or insufficient permission: the role is insufficient, or the knowledge-base key does not include the target knowledge base.
- 404 Not Found: wrong Base URL. Cloud uses
https://api.dify.ai/v1; self-hosting uses your own domain ending in/v1, without the full endpoint path. - Model unavailable from an endpoint: the provider key expired, the balance is short, or upstream is rate limiting; revalidate in model provider settings.
- Knowledge-base endpoint 404/403: an app key and a Service key were mixed up, or the knowledge base is outside the key's scope.
- 429 Too Many Requests: a rate limit was hit. Lower concurrency and retry with exponential backoff.
- Everyone signed out after changing SECRET_KEY: expected behavior, as described above; assess the impact first and do not simply revert to the old value.
Another common mistake: Dify runs in a container or in the cloud, but the configuration points at localhost or a private address. Dify cannot reach your local service, and no key will help. When a business system cannot reach self-hosted Dify, check DNS, firewall, reverse proxy, and certificates first.
FAQ
Can a model provider key and an app API key be swapped?
No. The former lets Dify call upstream models; the latter lets external systems call Dify apps. The endpoints, permissions, and billing targets all differ.
Can one app have several API keys?
Usually yes. A common practice is to split by environment or caller so keys can be disabled and traced separately. The exact entry point depends on your current version.
Can an app API key be limited to a knowledge base or a user?
An app key is scoped to the app and cannot be split by knowledge base; the user field only distinguishes end users and is not an authentication mechanism. When you need knowledge-base-level scoping, use a Service API key and select the scope.
Does changing SECRET_KEY affect model provider keys?
Provider and tool credentials are encrypted with the workspace RSA key, not directly by SECRET_KEY; but after a change users are signed out, file URLs stop working, and OAuth credentials cannot be recovered. Read the deployment documentation and take a backup before changing it in production.
After a self-hosted upgrade, keys suddenly stop working. What do I check first?
Compare .env.example with your existing .env for newly added variables, then confirm KEY_PROVIDER_TYPE and the storage backend have not changed. If the encryption method changed, old credentials cannot be decrypted and must be re-entered. Finally, check error codes in the application logs.
Next steps
Dify key management comes down to three sentences: tell the types apart, issue by least privilege, and treat rotation as a fixed process. If you want a unified OpenAI-compatible entry point and centralized model usage, you can register for the ZSQH AI Gateway; the model range and prices are listed at model pricing.
Related reading:
