Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท Sharing and Deployment

Authentication, Secrets and Security

Protect a Gradio app: login with auth, OAuth sign-in, environment secrets, upload limits, allowed_paths, input validation and safe file handling, with runnable stand-ins.

A public Gradio app is a public program that anyone on the internet can feed input to. Most of the time that is fine, but once your function reads files, calls paid APIs or touches private data, you must decide who may use it and what they may do. This lesson covers login, secrets and the mistakes that cause real leaks.

The real Gradio is not available on this site, so its code is read-only. Runnable blocks use plain Python to demonstrate password hashing, path checks and rate limiting, which are exactly the problems you solve around a Gradio function.

Password login

The simplest protection is a username and password list in launch():

Python
demo.launch(auth=[("alice", "s3cret-one"), ("bob", "s3cret-two")])

Visitors now see a login page before the app. Wrong credentials show an error message. You can also pass a function that decides:

Python
def check(username, password):
    return username in USERS and verify(password, USERS[username])

demo.launch(auth=check, auth_message="Staff only. Ask IT for an account.")

Inside an event handler, add a parameter of type gr.Request to learn who is calling: request.username holds the signed-in name, request.client.host the IP address and request.headers the HTTP headers. This is how you give each user their own data.

Basic login is good for small private tools. It does not offer password reset, 2-factor authentication or single sign-on. For public apps on Hugging Face you can add OAuth: place gr.LoginButton() in the layout, set hf_oauth: true in the Space README and declare profile: gr.OAuthProfile | None in your function to receive the visitor's Hugging Face profile. Real companies usually put the app behind their own identity provider (an auth proxy) and let the proxy handle sign-in.

Never hard-code passwords

The example above is only for explanation; real credentials belong outside the source, in environment variables:

Python
import os

USERS = {"alice": os.environ["ALICE_PASSWORD"]}

Store passwords as salted hashes when you keep them in a file. The block below shows the idea with the standard library; a stand-in because the site cannot run Gradio, but hashlib and hmac work as they do anywhere.

Python Hash and verify a password

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first check prints True, the second False. For real systems prefer a slow password hash (bcrypt, scrypt or argon2) rather than plain SHA-256, as it makes guessing expensive; this block is kept short for illustration.

Secrets and keys

  • Keep API keys in environment variables or the Space's secrets, never in the repository or the page text.
  • Never print or return a key, and do not show raw exceptions to visitors: they can contain URLs or headers with secrets. Catch errors and show a plain message.
  • If a key leaks, rotate it immediately. Removing it from a later commit does not remove it from Git history.
  • Your function can call a paid API on behalf of anonymous visitors. Add a spending cap at the provider and a request limit in your app.

Files and paths

Components that accept uploads store the file in a temp folder and hand you its path. Two settings decide which files Gradio may read or serve:

  • allowed_paths=["/data/public"] in launch() adds folders that can be served, outside the working directory.
  • blocked_paths=[...] blocks folders even inside the allowed area.
  • max_file_size="20mb" rejects oversized uploads.

Be careful when your function builds a path from user input. A name like ../../etc/passwd can escape the folder you meant. Resolve and check the path before opening it:

Python Block path traversal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first two names resolve under /srv/app/files; the third is rejected. In real code use Path.resolve() on the actual filesystem and compare with is_relative_to.

Limiting abuse

Open demos get hammered. Useful measures: the queue (max_size, concurrency), short maximum input lengths, per-user rate limits and daily budgets. A small in-memory limiter looks like this:

Python A per-user rate limiter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The fourth request (t=3) is blocked, and the call at t=61 is allowed because the earlier ones have aged out of the window. In a multi-process deployment a dictionary in memory is not shared, so use Redis or a database for the counters.

Other safety points

  • Never run user text as code. eval or exec on user input gives visitors your machine.
  • Escape what you show. gr.HTML and Markdown can render HTML; do not display raw user input in them without sanitizing it.
  • Pickle files are code. Loading an uploaded .pkl or an untrusted checkpoint can run arbitrary code.
  • Use HTTPS for anything with a login, and keep Gradio updated, since security fixes land regularly.
  • Treat share=True links as public, whatever your intentions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you require a username and password in Gradio?

    The auth argument takes a list of (username, password) pairs or a checking function.
  2. 2. How can a handler know which user is calling?

    A parameter annotated with gr.Request is filled in by Gradio with details of the call.
  3. 3. Where should API keys live?

    Keep keys out of source control and out of the UI.
  4. 4. What is the danger of joining user input to a folder path?

    Path traversal lets users read files outside the intended directory.

Summary

  • Use auth= (list or function) for simple login, OAuth or an auth proxy for more.
  • Keep secrets in environment variables; hash stored passwords.
  • Limit uploads, check paths, and rate-limit expensive functions.
  • Never eval user text, never unpickle untrusted files, and treat share links as public.

Next: The Gradio API and Python Client