Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 20. Authentication and Access Control

The workbench in the first nineteen chapters works the moment you have its address. This chapter adds a door to it. People who do not know the password cannot get in; those who do get in still see the same pages as before, plus one more page, Access.

Opening the door is two assignments.

demo.Auth = GradioAuth.Accounts([("alice", Password("alice")), ("bob", Password("bob"))]);
demo.AuthMessage = "This workbench is for me and one colleague only. The accounts have already been assigned; the passwords are on the machine that launches it.";

The other matter is API visibility, which decides whether a given API exposes its name and recognizes its name. This chapter treats the door and the curtain separately, and ends with what a visitor sees while the door is closed.

Why save this for Chapter 20? Because the examples in the first nineteen chapters all assume “only you are using it.” Session state (Chapter 14), the upload directory (Chapter 12), and the queue limit (Chapter 15) are all designed on the premise of “local machine, single user, trusted.” Adding a door does not turn those premises into “multi-user.” It only keeps people who should not get in from getting in. To truly share it among several people, what you change is how state and storage are divided, and that is work at another layer.

Let me set the boundary first, so expectations do not run ahead. What this chapter does is “add a door to a local application,” not build a user system. Registration, password recovery, roles, and auditing are all absent. Chapter 1 explained this positioning, and Chapter 14 also said “a session is not a user.” If you need those things, you have to move the accounts into a database and let a real identity service handle authentication, which is a different topic.

20.1 Single-Account and Multi-Account Authentication

Blocks.Auth takes a GradioAuth, and there are three ways to build one.

demo.Auth = GradioAuth.OneAccount("alice", "wonderland");
demo.Auth = GradioAuth.Accounts([("alice", "wonderland"), ("bob", "builder")]);
demo.Auth = GradioAuth.Verify(Check);   // covered in 20.2

After the assignment, demo.RequiresLogin is true. This property is read-only, for self-checks. Print one line to the log at startup and you know whether the door was opened this time.

The example uses the second form, one account for yourself and one for a colleague. The password is read from an environment variable, falling back to a demo value that runs as-is when it is not set; the demo value is written in the code, the real password is not.

static string Password(string name) =>
    Environment.GetEnvironmentVariable($"BOOK_{name.ToUpperInvariant()}_PASS") ?? $"{name}-demo";

demo.Auth = GradioAuth.Accounts([("alice", Password("alice")), ("bob", Password("bob"))]);

If BOOK_ALICE_PASS is set, it uses your own; if not, it is alice-demo. The example wants people to be able to run dotnet run and get straight in, so it keeps a default; when you put it to real use, set the environment variable and not one line of code has to change.

If the username, the password, or the list has any empty item, it throws ArgumentException on the spot. OneAccount("", "x") throws An account needs a username.; OneAccount("a", "") throws The account 'a' needs a password; an empty one admits anyone who guesses the name.; Accounts([]) throws An application protected by accounts needs at least one. The first two concern an empty username or password, the third an empty list. The messages are worded this bluntly because they are blocking a real accident: a password configured as an empty string lets anyone in.

The default deserves a mention of its own. alice-demo is there so that someone can git clone and get straight in; but it also means on a machine with no environment variable set, anyone can use that password to get in, and the UI looks no different. Login succeeds, the page is normal, everything goes smoothly. Before deploying on a shared machine, first confirm those two environment variables really are set. The self-check is simple. Try logging in once with alice-demo; if you cannot get in, they are set correctly.

Duplicate usernames do not throw; the later one overwrites the earlier one. In Accounts([("a","1"),("a","2")]), a/1 evaluates to false and a/2 to true. This is easy to trip over when changing a password. The list keeps the old line and the new one is written after it; it looks like both lines are there, but only the last one actually counts.

After you set Auth, anyone not logged in who opens any page gets this card.

Figure 20-1 With the door closed, a login card; on the card is that AuthMessage sentence

Note it appears on any page — /, /text, /access are all the same. It is not “the home page blocks you, the other pages let you through.” The card’s copy comes from AuthMessage, rendered as HTML, so you can put links and bold text in it; omit it and the page’s own default line is used.

What Happens Along the Login Path

The “Log in” button on the card sends POST /login with a form-encoded body and two fields, username and password. Success returns 200 and one line, {"success":true}, with two Set-Cookie headers in the response.

access-token-<suffix>=<token>; path=/; samesite=lax; httponly
access-token-unsecure-<suffix>=<token>; path=/; httponly

The two names differ by just the unsecure segment and hold the same token. The one with samesite=lax is for normal same-site requests; the one without is a fallback when “cross-site is rejected.” httponly means the page’s scripts cannot read it, so XSS cannot steal it. The suffix in the name is generated randomly at process startup, so old cookies naturally stop working after a restart. That suffix was originally meant to tell different processes apart; it has nothing to do with the security design.

After login the browser automatically sends both on every request, and the server recognizes you by the token. There is no JWT anywhere in this chain, no refresh token, and the cookies carry no expiry. The token lives in the server process, and a restart invalidates all of them. That is just right for a local application; delivering it to others calls for another approach.

You can walk this path with curl; it shows each step more clearly than clicking in the UI.

curl -i -X POST http://127.0.0.1:7860/login -d "username=alice&password=alice-demo"

On success you see those two Set-Cookie headers; on failure it is 400 and one line, Incorrect credentials. (details in 20.5). Add -c cookies.txt and you can then hit /config directly with the cookie, without opening a browser.

One thing to accept. The login card is not a page you drew. Its address, field names, cookie names, and failure copy are all fixed by the framework; the only thing you can change is that one sentence on the card (AuthMessage). Its appearance does follow the theme, though. After the frontend loads it fetches /theme.css on its own, so the card and the page you see after login share one color scheme (the example’s card is that purple). But its tab title is empty. The shell returned when not logged in has no <title>, so the browser tab shows the address.

The three forms, each with whom it suits, gathered together.

Figure 20-2 Three forms, but on the server they are the same thing: one login exchanges a pair of cookies, and every request after that carries them

Verify gets its own section next. Here let us first settle “when to use which.”

  • Only you use it: OneAccount. Changing the password means editing code and restarting.
  • You plus one or two colleagues: Accounts. One account each, so if something goes wrong you can tell who it was.
  • Accounts will change, or you need logging and rate limiting: Verify.

All three lack the same set of things: there are no roles (everyone is the same once inside), and there is no “remember me” or password-change entry point either. The two accounts in Accounts have exactly the same permissions. To split permissions you have to check Request.UserName yourself in the binding (used in 20.3), or simply run two applications.

In a multi-page application this door is global, not opened page by page. The example sets Auth once and every page is blocked together; there is no “this page is public, that page needs login.” To make part of the content public you have to run two applications, or judge Request.UserName yourself within one application. The latter is “dividing permissions among people inside the door,” which is a different matter from “whether the door opens.”

One consequence is easy to overlook. Someone not logged in cannot see the navbar. Navigation is part of the page content, and the empty shell has no content. So an outsider only knows the address is alive, not how many pages are behind it or what they are called. This says more about how “blocking” is implemented than the status code does: the page is sent back as usual, just with nothing inside it.

The timing of the assignment is the same as for themes: Auth must be set before Launch. Chapter 4 explained that the page is sealed on the first request; changing it after sealing has no effect and raises no error.

20.2 Custom Verification Functions

When accounts are not written in code, use Verify. It has two overloads.

GradioAuth.Verify(Func<string, string, bool> rule);
GradioAuth.Verify(Func<string, string, CancellationToken, ValueTask<bool>> rule);

The parameters are the name and password the user submitted, passed in as-is. The synchronous version suits “read a dictionary, compare a hash”; the asynchronous version suits “ask somewhere else,” querying a database or calling an identity service.

The example’s lab project gives the complete shape of the third form. Accounts live in accounts.json, the table stores the SHA-256 of the password, and the rule re-reads this file every time.

static bool Check(string userName, string password)
{
    var path = Path.Combine(AppContext.BaseDirectory, "accounts.json");
    if (!System.IO.File.Exists(path)) return false;

    var table = JsonSerializer.Deserialize<Dictionary<string, string>>(System.IO.File.ReadAllText(path));
    if (table is null || !table.TryGetValue(userName, out var expected)) return false;

    var actual = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(password)));
    return CryptographicOperations.FixedTimeEquals(
        Encoding.ASCII.GetBytes(actual),
        Encoding.ASCII.GetBytes(expected.ToUpperInvariant()));
}

The three decisions are these. First, re-read the file every time. Adding an account or changing a password needs no restart; the change takes effect on the next login. A real project swaps this block for a database query, edited the same way.

Second, compare hashes, not passwords. If the file leaks, what is taken is a hash, not a password you can use directly. SHA-256 without salt only suits this “two accounts on a local machine” case. The same password hashes the same way in two tables, and that can be seen. For proper storage, use a salted slow hash (PBKDF2, bcrypt, Argon2); that is a cryptography topic.

Third, compare with FixedTimeEquals. Ordinary == on strings returns at the first differing character, so the time depends on “how many leading characters match.” A fixed-length comparison walks both sides to the end, so the time depends only on length. Whether this can be exploited over a network depends on how much noise there is; but it costs only one extra method call to write, so there is no reason not to.

What you store the password as also depends on what it has to stop. The example’s accounts.json stores SHA-256, without salt. That stops “the file being glanced at in passing,” not “someone taking the file and computing at leisure.” The same password on two accounts computes to the same value; two identical rows of hash tell you those two people used the same password. To store it properly you need a salted slow hash. One random salt per account, a hundred thousand rounds of hashing, so that “one guess” goes from microseconds to tens of milliseconds. Rfc2898DeriveBytes.Pbkdf2 is in the standard library; no package to install.

A slow hash brings a new problem. One login takes tens of milliseconds, and an attacker guessing once also takes tens of milliseconds. That is a deliberate cost. When you really reach the scale where you must stop brute force, you add rate limiting, not turn the round count down.

A rule has to keep two conventions. One: only answer true/false; to reject, return false. Let the rule throw an exception and the browser gets a 500, with the error notice, retries, and logs all changing shape. Two: empty values are passed in as well. Run it once with a rule that only prints its parameters. Submit empty strings for both username and password, and the rule receives two empty strings; the framework does not screen them out for you first. So “reject an empty password outright” is something you write yourself, or you let the hash comparison handle it. The hash of an empty string does not equal any record, so it is naturally false.

When you need to ask somewhere else, switch to the asynchronous version; the shape is the same, you just turn “look up” into “wait for.”

GradioAuth.Verify(async (userName, password, cancellation) =>
{
    var record = await Accounts.FindAsync(userName, cancellation);

    // When the name does not exist, run once against a fixed dummy record; the timing matches a real record, so you cannot ask whether the account exists.
    var salt = record?.Salt ?? Hasher.DummySalt;
    var expected = record?.Hash ?? Hasher.DummyHash;

    var hash = await Hasher.SlowHashAsync(password, salt, cancellation);
    return record is not null && CryptographicOperations.FixedTimeEquals(hash, expected);
});

When two login requests arrive at the same time, the rule is called twice at once. It is an ordinary handler function, not a queued task. So if the rule counts failures or writes a log file, think through the concurrency first; increment with Interlocked, or just write the count into a database.

CancellationToken is the one for when the request is cancelled. Closing the browser page or a request timeout triggers it. A database-backed implementation has to pass it down, otherwise one stuck login holds a connection open.

Besides “judging right or wrong,” a rule can also do a few things the framework does not manage: write one line of log (who, when, succeeded or not), count failures by source, shut out sources with repeated failures, and let only certain accounts in during a maintenance window. That is what “your own rule” is for. Accounts does one thing; Verify can do anything, at the price that you also own the mistakes.

The lab project switches among four cases with an environment variable, so you can compare them directly.

$env:BOOK_AUTH="one"       # one account (password alice-demo)
$env:BOOK_AUTH="accounts"  # a set of accounts: alice and bob, passwords are the name plus -demo
$env:BOOK_AUTH="verify"    # reads accounts.json, compares hashes
$env:BOOK_AUTH="none"      # no Auth is set, anyone can get in
dotnet run --project samples-en\chapter20\lab

A custom rule has four kinds of input to walk through first: the correct account and password, a correct account with a wrong password, an account that does not exist, and both empty strings. The fourth falls through naturally to false when there is no dedicated branch. The hash of an empty string does not equal any record, so the comparison gives false; but if the rule contains a branch like “if the name is empty, let it straight through,” that becomes a successful login, and the UI shows nothing unusual.

The none case is not there just to fill out the list; it lets you see what “no door” looks like. The page is the complete workbench directly, and Request.UserName in the handler function is null. Adding or not adding authentication does not change one character of component code; that is a fact the next sections use again and again.

20.3 The Login Button and Logged-Out Behavior

The login card is not drawn by your page. It is an empty shell page drawn by the frontend. When not logged in, the HTML the server returns has window.gradio_config carrying auth_required: true and auth_message, while components and dependencies are both empty and pages holds only one empty string. Seeing auth_required, the frontend does not draw your UI and draws a form instead.

This also explains something easy to misunderstand. Visiting /text when not logged in gives HTTP status 200, not 403. The page itself has to open before the login card can be drawn. What blocks the content is this empty shell, with nothing inside it.

The name gr.LoginButton makes it easy to assume it is “the login button for password authentication.” It is not. It belongs on the OAuth path. Its default text is Sign in with Hugging Face, and clicking it sends the browser to /login/huggingface. That address is registered by the button itself. With no gr.LoginButton on the page it is 404; put the button there without an OAuth provider configured and it returns 500. Not 404, and not a “not configured” line either. On a page holding only this button, after login the button text still has not changed to “Log out,” and clicking it still heads for that 500.

Someone will ask: why not just use HTTP Basic authentication? The browser brings its own dialog, and not one line of configuration is needed. Three reasons. One, that dialog is not yours to control: you cannot change its copy, cannot put a link in it, and cannot even write “what this application is called” into it. Two, you cannot log out. Basic credentials are cached by the browser and the standard has no “log out” action; close the tab, open it again, and you are still logged in. Three, it sends the password along with every request, instead of a token that can be revoked.

The framework chose a form plus cookies. One extra request buys a customizable card, a link that really logs out, and a token the server remembers.

So applications using password authentication do not use it. The example places not one. When the “log in” action is needed, what the user does is fill in the account on the card, and the framework has already supplied that card.

Conversely, logging out has no button, but it has an address, /logout. Open it with the cookie and the server clears those two cookies in the browser, then 302s back to the home page; the home page becomes the login card again. The example puts this on the Access page.

gr.HTML("""<a href="/logout">Log out</a>""");

There is one detail here. Do not use a Markdown link. [Log out](/logout) renders an <a> with target=_blank, so clicking opens a new tab. The new tab is back at the login card, while the original tab still holds the old content, which looks as if logging out failed. A hand-written <a> has no such attribute and navigates away in the current page. Try each of the two forms once; the difference is exactly that one attribute.

Logging out also invalidates this account’s token. This runs against the “only clears cookies” intuition; you only see it clearly by running the experiment. Log in, note the cookie value, /logout, then put that same pre-logout value back into the request header. /config returns 401, /gradio_api/user returns null. The server has deleted the token straight out of memory.

The scope of invalidation is the account, not this one login. Open two tabs, log in once in each with the same account, and you get two different tokens; log out one of them and the other also returns 401. Log in with a different account (bob), and after logging out alice, bob is still 200; invalidation goes by username.

The exception is an application with gr.LoginButton on the page. Then /logout is handled by the OAuth route, and old tokens still return 200 after logout (a page holding only that button verifies it). The example places none, so everything in this section is about the password-authentication path.

Restarting the application invalidates all tokens at once. They live only in the process’s memory and are never written to disk. To take the account in the current browser offline immediately, log out; to take all accounts offline together, restart.

After a successful login the page content is replaced, but the address does not change. In the example you log in at /access and are still at /access afterward; only the login card has become that page’s body. This page change is a full reload. The path in the address bar is kept as-is, so deep links and the current page survive; but temporary state in the page that was not submitted is refreshed away. Hang a marker on window before login and after login it is gone.

After login, “who is operating” is available on the server side: add a Request to the handler function’s parameter list.

Func<Request, object> answer = request =>
{
    var name = request.UserName ?? "(empty)";
    return $"**Who is operating** username `{name}`, session `{request.SessionHash}`.";
};

ask.Click(answer, null, [who], apiName: "Ask identity");

Request is not a component and does not go into inputs. It is an extra parameter the framework injects by type; you can write it at any position in the parameter list, or write only it. UserName is the logged-in account behind this run, SessionHash is the session id (Chapter 14). When the application does not require login, UserName is null. That is what the none case at the end of 20.2 looks like.

Figure 20-3 The home page after login; when not logged in, the same address gives only the login card

Figure 20-4 The Access page: the top line is Request.UserName, and the three buttons below differ only in apiVisibility

Putting identity into the UI has another use. With several accounts, write one line on the page, “current account alice,” and the user knows whose session they are using. That is not a small thing when several people share one machine. Chapter 14 counts a session as “one page load,” so two people each opening a tab have two separate states; who changed what can only be matched up by the session id. Session state (Chapter 14) is divided by session; switch accounts and it is a different one. If you do not write this out, users will think “my input was lost.”

20.4 Authentication and API Visibility Layered Together

Everything so far has been about “blocking the page.” The page is only one entry point; the API has to be defended too. A script does not need your page — it just POSTs directly.

What does the API give when not logged in? 401, plus one line for the frontend to display.

{"detail":{"error":"Not authenticated","auth_message":"This workbench is for me and one colleague only. The accounts have already been assigned; the passwords are on the machine that launches it."}}

This auth_message is AuthMessage, so you write the custom notice in one place and both the page and the API follow. The list is “APIs outside the page”: /config, /gradio_api/info, /gradio_api/queue/join, /gradio_api/run/..., /gradio_api/call/..., /gradio_api/file=... are all behind this gate; outside the door are the things the login page needs itself — the theme stylesheet /theme.css, frontend assets, /login, /logout.

Two exceptions. /gradio_api/user returns 200 even when not logged in, with null as its content (“no one” is also an answer); /gradio_api/login_check returns 401 when not logged in, and after login 200 plus a null. The frontend uses these two addresses to decide “whether to draw the login card.”

The two answers, page and API, set side by side.

Figure 20-5 The same door, two ways of answering: the page gives an empty shell, the API gives 401

So “blocking the page” and “blocking the API” are not the same thing, and not one gate either. The page works by “giving no content,” the API by status code; the only way to skip login by editing the frontend is to call the API, and the API judges for itself.

Once the door is open, the second layer comes into play: API visibility. apiVisibility on a binding has three values.

Figure 20-6 Visibility governs the API, not the UI; all three buttons can be clicked on the page

  • ApiVisibility.Public (default), enters /gradio_api/info, and can be called by name.
  • ApiVisibility.Undocumented. Does not enter /info, but can be called by name, and once you get the event_id you carry on as usual.
  • ApiVisibility.Private. Does not enter /info, calling it by name returns 404, with the body Could not infer function index for API name: Visibility private.

Note that 404 line. It says “this name is not recognized,” not “you have no permission.” That is deliberate. To the frontend a private endpoint does not exist, and it gives the same answer as “this name is misspelled,” so someone probing names cannot work out which name is real.

/gradio_api/info is that list. When someone else wants to write a script against you, the first step is to fetch it and see which endpoints exist. So “whether to expose” amounts to “whether this counts as your public API.” Setting an intermediate step to Private says “this step is internal to the UI, do not use it as an API”; setting it to Undocumented says “it works, but is not recommended and not guaranteed.”

The order in which the three layers stack is: authentication → visibility → handler function. Authentication is the outermost; without logging in you cannot even ask “does this name exist” (401, not 404); only after login does visibility say “whether this name is exposed and recognized.”

Why can all three buttons on the page be clicked? Because page submission goes through /gradio_api/queue/join carrying an fn_index, not a name. Visibility governs “names,” and the UI uses no names, so it cannot stop your own people from clicking the buttons. That is by design, not a hole. Private is a boundary set for scripts, not for users.

In the example the three buttons’ bindings differ only in apiVisibility; their names are all different.

open.Click(() => "**Public** listed in `/gradio_api/info`, and callable by name.", null, [result],
    apiName: "Visibility public");
undoc.Click(() => "**Undocumented** not in `/info`, but callable by name.", null, [result],
    apiName: "Visibility undocumented", apiVisibility: ApiVisibility.Undocumented);
closed.Click(() => "**Private** not in `/info`, and calling it by name is not recognized — the UI still works.", null, [result],
    apiName: "Visibility private", apiVisibility: ApiVisibility.Private);

apiName is required. Visibility is about “whether this name is exposed,” and with no name there is nothing to talk about. How names are formed and what the framework puts together when you omit one is covered in Chapter 22.

To verify, you do not need to open the UI; use the three curl commands below (the details of job-style calls are also in Chapter 22).

curl -s -b cookies.txt http://127.0.0.1:7860/gradio_api/info        # list which names are in the list
curl -s -b cookies.txt -X POST http://127.0.0.1:7860/gradio_api/call/%E5%8F%AF%E8%A7%81%E6%80%A7%E5%85%AC%E5%BC%80 -d '{"data":[]}' -H "Content-Type: application/json"
curl -s -b cookies.txt -X POST http://127.0.0.1:7860/gradio_api/call/%E5%8F%AF%E8%A7%81%E6%80%A7%E7%A7%81%E6%9C%89 -d '{"data":[]}' -H "Content-Type: application/json"

Those two strings in the path are the UTF-8 percent-encoding of Visibility public and Visibility private. Write non-ASCII characters directly into the URL and Kestrel returns 400 before routing, with an empty body. The reason is that the request line itself is invalid, and has nothing to do with authentication.

The first returns the endpoint list; the second an event_id; the third 404 and that Could not infer function index line. Without the cookie all three are 401, so do not forget the order.

How to choose in practice: default to Public; use Private for bindings only your own page uses (say an intermediate step), so nobody treats it as an API; use Undocumented for “works, but I do not want it in the docs.” The example’s Access page puts the three buttons side by side precisely so this difference is visible in a single UI.

20.5 How Authentication Failures Are Presented

Type the password wrong and the user sees something like this.

Figure 20-7 Bad credentials: a red line above the card, both input boxes cleared, focus left on the login button

That red line on the card does not come from the server. The server sends 400 plus one English line, Incorrect credentials.; what the card shows is a line the frontend translated itself, “Incorrect credentials.” It maps by status code and does not read the body. Replace the 400 body with some other English sentence and submit again, and the card still shows those same words. This has two consequences. Changing AuthMessage does not change the failure notice (that sentence appears only on 401 and at the top of the card); to give “Incorrect credentials.” different wording, you edit the frontend language pack, not this.

What the backend gives is 400, one body line.

{"detail":"Incorrect credentials."}

This line is identical character for character in three cases: wrong password, username that does not exist, empty password. Compared three responses byte by byte with curl, all are 35 bytes, the bodies exactly the same. That is how “not leaking whether an account exists” is done. If a nonexistent username returned “User not found,” an attacker could first screen a list of email addresses, then try passwords only against accounts that exist.

Besides explicit failure there is a category of “the format is simply wrong.” When the request has no username or password field at all, it returns 422.

{"detail":[{"type":"missing","loc":["body","username"],"msg":"Field required","input":null},
           {"type":"missing","loc":["body","password"],"msg":"Field required","input":null}]}

The two need to be told apart. 422 means “you did not submit in the right format,” 400 means “you submitted, but it is wrong.” The frontend only translates 400 into “Incorrect credentials.”; 422 is not reachable on the normal path. The two boxes on the card always submit.

Accounts and OneAccount answer the same way because outwardly they answer only one question: do these credentials work. Name does not exist, password wrong — the answer is false either way, with exactly the same status code and body. They do not promise the timing is the same too; to control timing as well, use Verify, compute a hash first, then look up the table and compare.

When you write Verify yourself, you have to guarantee these two things: the same answer, and timing as close as possible. The counterexample is common.

// Don't write it this way: returning early when the name does not exist makes the timing different from "name exists but password is wrong"
var record = table.FirstOrDefault(x => x.UserName == userName);
if (record is null) return false;
return SlowHash(password, record.Salt) == record.Hash;

When the name does not exist, not one slow hash is computed; when it exists, one is. That time lands on the response, and averaging over many requests makes it distinguishable. Swap the order: compute the hash first, then look up the table and compare; compute it as well when the name does not exist.

Two more things that are easy to get wrong. One: do not lock by username. “Lock for ten minutes after five wrong tries” sounds safe, but what do you return while locked? Return “Account locked” and you have told the other side the account exists; return “Incorrect credentials.” and the user does not know they are locked. For a local application, simply do not lock at all; if you must, do it by source IP and accept the collateral damage that brings.

Two: do not write passwords into logs. Verify receives the plaintext password, and a casual Console.WriteLine is convenient, but logs get copied and pasted into chat windows. If you log, log the name, the time, and the result — not the password.

One last distinction. A failed login does not produce the error block from Chapter 17. That block pops up when a run in the queue fails, and login never enters the queue. It happens before the page gets its config, when the frontend has not even drawn your UI yet. So the notice for bad credentials is on the card and the notice for run-time errors is in the panel: two separate things; do not expect to see them in one place.

One last point about the current state: login has no rate limiting. Repeated wrong tries do not slow down, do not lock, and do not raise a CAPTCHA. Two people on a local machine are fine; the day you put it on an intranet, put a reverse proxy in front for rate limiting, or count by source yourself inside Verify. The framework offers no rate-limiting configuration item, and there is no such implementation in the code.

20.6 Chapter Summary

After adding a door, the changes land in these places.

  1. One line, demo.Auth = GradioAuth.Accounts(...), opens the door. The three forms (OneAccount, Accounts, Verify) cover “just you,” “a few colleagues,” and “accounts stored elsewhere.” An empty password throws on the spot; a duplicate username is overwritten by the later one.
  2. The door and the curtain are two layers. Authentication decides “whether you can get in,” visibility (apiVisibility) decides “whether this name is exposed and recognized.” Authentication is the outermost; without logging in you cannot even ask about a name.
  3. Page 200, API 401. When not logged in the page is still sent, but it is an empty shell (auth_required: true, components and bindings all empty); the APIs uniformly return 401 with auth_message in the body. Blocking the page is not blocking the API.
  4. Failure is always the same one line. Wrong password, nonexistent user, empty password — all 400 Incorrect credentials., byte for byte. A custom rule has to hold this line itself, and also hold “compute the hash before looking up the table.”
  5. What logout invalidates is the account. /logout clears those two cookies in the browser, the server deletes this account’s token along with them, and replaying the old cookie returns 401; another tab of the same account fails together with it, while other accounts are unaffected.

This chapter only handles “who can get in.” How to coexist with the host once inside, and how to expose capabilities as APIs, are Chapters 21 and 22 respectively.

The cost of this chapter should be stated too: one more password to maintain (or one more account table), one more deployment risk of “forgot to set the environment variable,” and one more boundary to remember in “logout invalidates by account, restart invalidates by process.” What you get in return is that when you send the address out, you no longer have to worry that the recipient will casually click it open and see your drafts and records.

Finally, a self-check list; go through it in order when you wire this into your own application.

  • Print one line of RequiresLogin in the startup log to confirm the door really opened this time;
  • Open every page in a browser that is not logged in and confirm all you see is the login card;
  • Use curl to hit /config and one apiName directly and confirm both are 401, not 200;
  • After login, open /gradio_api/info and count the exposed endpoints to see they match expectations;
  • Log out, open the page again, and confirm you are back at the card;
  • Change one sentence of AuthMessage and confirm both the page and the 401 carry the new sentence.