Sub topic 15
Adding authentication and basic security
This chapter covers how to protect a Gradio chat app once it leaves your laptop. It assumes you can already build a gr.ChatInterface, launch it, and understand server_name, server_port, and share links from the previous chapter. You should also be comfortable with environment variables and basic HTTP concepts such as ports and headers.
What you are protecting
A chat app usually holds three things worth protecting:
- The backend API key. If the app calls an LLM, every visitor spends your money.
- The conversation content. Users may paste private data into the box.
- The host machine. The Python process can read files and reach your network.
Authentication answers "who may use this app?". It does not answer "what may they do once inside?". You need both.
Binding the server: who can reach it
By default, launch() binds to 127.0.0.1. Only your own machine can connect. This is the safest setting for development.
Setting server_name="0.0.0.0" binds to every network interface. You need this inside a container, because traffic arrives from outside the container's loopback address. It also means anyone who can reach the port can reach the app.
| Setting | Who can connect | Typical use |
|---|---|---|
| `server_name="127.0.0.1"` (default) | Only the local machine | Development |
| `server_name="0.0.0.0"` | Any host that can route to the port | Containers, servers |
| `share=True` | Anyone with the public link | Quick demos |
A share link is a public URL that tunnels to your machine. Treat it as publishing the app on the internet. Links expire after a limited time, but while one is active, anyone who has the URL can use the app unless you also set auth.
Adding a username and password
The auth argument of launch() puts a login page in front of the whole app. Read the credentials from environment variables so they never appear in source control.
import os
import gradio as gr
def respond(message, history):
return f"You said: {message}"
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
auth=(os.environ["CHAT_USER"], os.environ["CHAT_PASSWORD"]),
)Set the variables in the shell before you start the script:
export CHAT_USER="alice"
export CHAT_PASSWORD="a-long-random-passphrase"
python app.pyIf a variable is missing, os.environ[...] raises KeyError and the app refuses to start. That is the behavior you want. An app that silently falls back to no password is worse than one that crashes.
Several users
auth also accepts a list of (username, password) tuples:
import os
import gradio as gr
def respond(message, history):
return f"You said: {message}"
demo = gr.ChatInterface(fn=respond, type="messages")
users = [
(os.environ["CHAT_USER_1"], os.environ["CHAT_PASS_1"]),
(os.environ["CHAT_USER_2"], os.environ["CHAT_PASS_2"]),
]
if __name__ == "__main__":
demo.launch(auth=users)A custom check function
For anything beyond a handful of fixed accounts, pass a function that receives the username and password and returns True or False. Compare secrets with hmac.compare_digest to avoid timing differences, and store hashes instead of plain passwords.
import hashlib
import hmac
import os
import gradio as gr
# Maps username to the SHA-256 hex digest of the password.
# In a real deployment, load this from a secret store or database.
USERS = {
"alice": hashlib.sha256(os.environ["ALICE_PASSWORD"].encode()).hexdigest(),
}
def check_login(username, password):
expected = USERS.get(username)
if expected is None:
return False
supplied = hashlib.sha256(password.encode()).hexdigest()
return hmac.compare_digest(expected, supplied)
def respond(message, history):
return f"You said: {message}"
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch(auth=check_login)Plain SHA-256 is fast, which makes it a weak choice for real password storage. For a production user database, use a slow password hash such as bcrypt or argon2. The example shows the structure of a check function, not a complete credential system.
Knowing who is asking
Inside a chat function, you can ask Gradio for the logged-in user by adding a gr.Request parameter. Gradio fills it in automatically, and it does not appear in the UI.
import gradio as gr
def respond(message, history, request: gr.Request):
user = request.username or "anonymous"
return f"Hello {user}, you said: {message}"
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch()request.username is None when no login is configured. With auth set, it holds the name that passed the check. Use it for audit logs, per-user rate limits, or choosing a per-user system prompt. The request object also exposes headers and the client address, which is useful for logging but should not be trusted blindly when the app sits behind a proxy, since headers such as X-Forwarded-For can be forged by clients unless your proxy overwrites them.
Limits of built-in authentication
Gradio's auth is a convenient gate. It has real limits:
- No encryption by itself. Without HTTPS, the password travels in clear text. Anyone on the network path can read it.
- No lockout or rate limiting. Nothing stops repeated guessing, so use long random passwords.
- No roles. Every logged-in user can use every feature.
- No single sign-on. There is no built-in connection to corporate identity providers.
For HTTPS, put a reverse proxy such as Nginx or Caddy in front of the app, or use a hosting platform that terminates TLS for you. For single sign-on, put an authenticating proxy in front, or mount the Gradio app inside a FastAPI app and use FastAPI's dependency system for authentication. Hosting on Hugging Face Spaces gives you some built-in access options, such as private Spaces.
Protecting secrets
The most common leak is the API key. Follow these rules:
- Read keys from environment variables or a secret manager, as the OpenAI client does with
OPENAI_API_KEY. - Never write keys in source files, notebooks, or Dockerfiles.
- Never pass a key through
additional_inputsas a visible textbox unless each user supplies their own key. Textbox values travel from the browser to the server, and the app's API makes them part of ordinary requests. - Keep
.envfiles out of version control with.gitignore. - Do not return raw exception text to the user. It can contain URLs, headers, or parts of requests.
The last rule connects to error handling. Catch backend errors, log the details on the server, and raise a short gr.Error for the user:
import logging
import gradio as gr
logger = logging.getLogger(__name__)
def call_backend(message):
raise RuntimeError("connection to https://internal.example/v1 failed")
def respond(message, history):
try:
return call_backend(message)
except Exception:
logger.exception("Backend call failed")
raise gr.Error("The assistant is unavailable. Please try again later.")
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch()Basic hardening checklist for the chat function
Authentication decides who gets in. The chat function must still treat input as untrusted.
- Limit input size. A user can paste a huge message and run up token costs. Check
len(message)and raisegr.Errorabove a limit. - Limit history length. Trim old turns before you build the LLM request, so one long session cannot grow without bound.
- Cap concurrency. Gradio queues requests. Use
demo.queue(default_concurrency_limit=...)to bound how many run at once, and set a maximum token count on the LLM call. - Never execute model output. Do not pass the reply to
eval,exec, or a shell. A model can be steered by user text into producing harmful commands. - Treat uploaded files as hostile. If you accept files, check their type and size, and do not open them with tools that execute content.
- Do not trust the system prompt as a secret. Users can often coax a model into repeating it. Keep nothing sensitive in it.
A function that applies the first two limits:
import gradio as gr
MAX_CHARS = 2000
MAX_TURNS = 10
def respond(message, history):
if len(message) > MAX_CHARS:
raise gr.Error(f"Message too long. Limit is {MAX_CHARS} characters.")
recent = history[-MAX_TURNS * 2:]
return f"You said: {message} (kept {len(recent)} earlier messages)"
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.queue(default_concurrency_limit=4).launch()Protecting the API endpoint
The login covers the API as well as the web page. A gradio_client caller must authenticate, or its requests are rejected:
import os
from gradio_client import Client
client = Client(
"http://127.0.0.1:7860/",
auth=(os.environ["CHAT_USER"], os.environ["CHAT_PASSWORD"]),
)
print(client.predict("Hello!", api_name="/chat"))If you do not want the endpoint to be callable by scripts at all, you can hide the API documentation page with launch(show_api=False). This only hides the documentation. It does not block calls, so authentication is still the real control.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `KeyError: 'CHAT_USER'` at startup | Environment variable not set in this shell | Export it, or pass it to the container with `-e` |
| Login page loops back to itself | Browser blocks cookies, or a proxy strips them | Allow cookies for the host, check proxy settings |
| App reachable from other machines unexpectedly | `server_name="0.0.0.0"` with no `auth` and no firewall | Add `auth` and restrict the port |
| `gradio_client` gets a 401 or login error | Client created without credentials | Pass `auth=(user, password)` to `Client` |
| Key visible in browser tools | Key placed in a textbox or in client-side code | Move it to a server-side environment variable |
Exercise
You deploy a chat app in a container with launch(server_name="0.0.0.0", share=True) and an OpenAI key in an environment variable. A teammate says the key is safe because it is not in the source code. What is still wrong, and what two changes would you make?
Show answer
The key is not exposed in the source, but the app has no authentication. With share=True and server_name="0.0.0.0", anyone with the public link or network access can chat, and each message spends your API quota. Add auth with credentials read from environment variables, and put HTTPS in front of the app, for example with a reverse proxy. Also remove share=True if you do not need a public link, and add input length limits and a concurrency limit to bound cost.
Exercise
Why does the chat function in this chapter catch exceptions and raise gr.Error with a fixed message instead of letting the exception reach the user?
Show answer
Raw exception text can contain internal URLs, request details, or other sensitive information. Logging the full exception on the server keeps the details available to you, and the fixed gr.Error message tells the user something went wrong without leaking them.
Exercise
Write the launch call that requires a login using credentials from CHAT_USER and CHAT_PASSWORD, limits concurrent runs of the chat function to 2, and hides the API documentation page.
Show answer
demo.queue(default_concurrency_limit=2).launch(auth=(os.environ["CHAT_USER"], os.environ["CHAT_PASSWORD"]), show_api=False). The queue call returns the demo object, so launch can be chained after it.