Hands holding a tablet beside an open laptop at a round table, banner image on the Auth explained for app builders page

HiringsAI blog

Auth explained for app builders

Sessions and cookies, hashing, login defenses, reset flows, MFA, OAuth and magic links, the ownership bug, roles, attacks in plain language, and the ten-minute review drill.

01

The short answer

Auth is two different questions wearing one word.

Authorization, what are you allowed to doAnswered on every request by checking who you are against what you own and what role you hold.
The machinery that ties it together in a web app is smallA login that proves identity once, a session, a random, unguessable ID stored in a cookie, that proves it on every later request, and server-side checks that never trust what the browser claims.
In this article, 42 sections The short answer Two questionsOne word Why auth deserves your review hours The stateless foundation Sessions: proving it once, then proving it cheaply A login, watched end to end Cookies: the transport, with its guards Passwords: hashed, not encrypted, never stored The login form is a security surface Password reset: the back door next to the front door MFA: the second proof Tokens and API keys: sessions for machines Rate limiting beyond the login form What the OAuth provider actually returns OAuth: borrowing an identity Magic links and one-time codes Authorization: the second question, answered per request The ownership bug: the one to hunt Roles: when ownership is not enough Sessions under attack: theft, fixation, and the guards Re-authentication for the moments that matter Testing auth as two users What the builder generates, and the ten-minute review The middleware habit: one gate, not fifty Email: the identity backbone you did not choose Auth state in the UI: what the user sees Logging: the auth events you will wish you had Sessions versus tokens, honestly Timing attacks and safe comparison Abuse beyond the account: the unauthenticated surface Third-party auth libraries: standing on maintained ground Session hygiene: expiry and cleanup Common attacks in plain language Auth and your database meet here Regulations and promises, at awareness level When to outsource auth entirely A worked review: generated login, line by line Common confusions, untangled Vocabulary that makes auth legible Frequently asked questions The bottom line Sources for the factual claims

The short answer

Auth is two different questions wearing one word. Authentication: who are you, answered by something you know, a password, something you have, a phone or a security key, or someone who vouches for you, Sign in with Google. Authorization: what are you allowed to do, answered on every request by checking who you are against what you own and what role you hold. The machinery that ties it together in a web app is small: a login that proves identity once, a session, a random, unguessable ID stored in a cookie, that proves it on every later request, and server-side checks that never trust what the browser claims. Your AI builder generates all of it, and auth is the one area where plausible-looking generated code can be quietly wrong in ways that hurt real people, so this article gives you the model to review it: how sessions and cookies actually work, why passwords are hashed rather than encrypted, why login errors must be vague and resets must not leak who has an account, what OAuth delegates, and the single most common authorization bug, checking that someone is logged in without checking that the thing belongs to them.

In this article - 42 sections
02

Two questions, one word

Keep the split clean, because every auth confusion is one of these leaking into the other.

Keep the split cleanKeep the split clean, because every auth confusion is one of these leaking into the other.
Authentication is identity, the login screenThe code from your email, the Google button, all answering who are you.
Authorization is permission, can this user edit this documentSee this dashboard, refund this payment, answered per action, not per session.
A logged-in user is an authenticated userA logged-in user is an authenticated user, whether they may touch the thing they are asking for is a separate, second check.
Apps get breached through both doorsApps get breached through both doors, but the quieter door is the second, an app that checks identity carefully and ownership carelessly lets any user walk into any other user's data by asking for it. authentication: who are you? password, second factor, or a provider vouching authorization: may you do this? ownership and role, checked per request both checks, every request server-side, against server data The quiet breaches come through the second door

Two questions, one word

Keep the split clean, because every auth confusion is one of these leaking into the other. Authentication is identity: the login screen, the code from your email, the Google button, all answering who are you. Authorization is permission: can this user edit this document, see this dashboard, refund this payment, answered per action, not per session. A logged-in user is an authenticated user; whether they may touch the thing they are asking for is a separate, second check. Apps get breached through both doors, but the quieter door is the second, an app that checks identity carefully and ownership carelessly lets any user walk into any other user's data by asking for it.

authentication: who are you?password, second factor, or a provider vouchingauthorization: may you do this?ownership and role, checked per requestboth checks, every requestserver-side, against server dataThe quiet breaches come through the second door

03

Why auth deserves your review hours

Of everything an AI builder generates, auth is where your attention earns the most, for a structural reason: the failures are silent and asymmetric.

Of everything an AI builder generatesOf everything an AI builder generates, auth is where your attention earns the most, for a structural reason: the failures are silent and asymmetric.
A broken hero section announces itself to everyoneBroken auth announces itself to no one, it works perfectly for the honest users while holding the door for the dishonest ones.
This does not mean auth is beyond youThis does not mean auth is beyond you, every mechanism in this article is small and checkable, it means the review sections are the point, and "it let me log in" is where verification starts, not where it ends.

Why auth deserves your review hours

Of everything an AI builder generates, auth is where your attention earns the most, for a structural reason: the failures are silent and asymmetric. A broken hero section announces itself to everyone; broken auth announces itself to no one, it works perfectly for the honest users while holding the door for the dishonest ones. And the blast radius is not yours alone: leaked credentials and exposed records belong to your users, people who trusted a form on a page you shipped. This does not mean auth is beyond you, every mechanism in this article is small and checkable, it means the review sections are the point, and "it let me log in" is where verification starts, not where it ends.

04

The stateless foundation

HTTP, the protocol every web request speaks, is stateless: each request arrives alone, with no memory of the requests before it.

HTTP, the protocol every web request speaks, is statelessEach request arrives alone, with no memory of the requests before it.
MDN's authentication guideMDN's authentication guide shows the protocol's own answer to identity, a challenge and response flow: the server replies 401 Unauthorized with a WWW-Authenticate header naming the scheme it accepts; the client retries with an Authorization header carrying credentials.
Modern apps rarely use the popupModern apps rarely use the popup, they draw their own login forms instead, but the shape it teaches is permanent: every single request must carry its own proof, because the protocol remembers nothing.

The stateless foundation

HTTP, the protocol every web request speaks, is stateless: each request arrives alone, with no memory of the requests before it. MDN's authentication guide shows the protocol's own answer to identity, a challenge and response flow: the server replies 401 Unauthorized with a WWW-Authenticate header naming the scheme it accepts; the client retries with an Authorization header carrying credentials. That framework is why the header and the status code exist, and the browser's old gray password popups, Basic authentication, are the simplest scheme in it. Modern apps rarely use the popup, they draw their own login forms instead, but the shape it teaches is permanent: every single request must carry its own proof, because the protocol remembers nothing.

05

A login, watched end to end

Follow one login all the way through, and every later section hangs on a frame.

Follow one login all the way throughFollow one login all the way through, and every later section hangs on a frame.
You type an email and password and submit
The server finds the user row by email, hashes what you typedThe server finds the user row by email, hashes what you typed, And compares it with the stored hash.
On a match it creates a session rowOn a match it creates a session row, a random ID pointing at your user ID with an expiry, and replies with that ID in a Set-Cookie header carrying the guards.
On your next click, the browser attaches the cookie unpromptedThe server looks up the session ID, finds it unexpired, and knows which user is asking, all before the page's own logic runs.

A login, watched end to end

Follow one login all the way through, and every later section hangs on a frame. You type an email and password and submit. The browser sends them over TLS to the server. The server finds the user row by email, hashes what you typed, and compares it with the stored hash. On a match it creates a session row, a random ID pointing at your user ID with an expiry, and replies with that ID in a Set-Cookie header carrying the guards. Your browser stores the cookie. On your next click, the browser attaches the cookie unprompted; the server looks up the session ID, finds it unexpired, and knows which user is asking, all before the page's own logic runs. When you log out, the session row is deleted and the cookie cleared; the same cookie presented afterward is just a string. Nine small steps, no magic, and each one maps to a check in the review drill.

login onceserver verifies password hashsession createdrandom ID + user ID + expiry, stored server-sidecookie carries the IDbrowser attaches it to every requestlogout deletes the server record; the cookie becomes a souvenir

06

Cookies: the transport, with its guards

The session ID rides in a cookie, and MDN's cookie documentation is blunt about the default: cookie values are visible to and changeable by the end user, so a stolen or tampered session ID is a stolen identity, a criminal who gets your session cookie can present it and be you.

The session ID rides in a cookieThe session ID rides in a cookie, and MDN's cookie documentation is blunt about the default: cookie values are visible to and changeable by the end user, so a stolen or tampered session ID is a stolen identity, a criminal who gets your session cookie can present it and be you.
The guards are cookie attributes set when the cookie is created
Secure: only send it over HTTPS never plaintext HTTP
HttpOnly, keep it away from JavaScriptHttpOnly, keep it away from JavaScript, So an injected script cannot read it.
SameSite, control whether it rides along on cross-site requestsStrict or Lax meaning a request triggered from another site arrives without your session, which is the main defense against cross-site request forgery, the attack where another page makes your browser send a request you never intended.

Cookies: the transport, with its guards

The session ID rides in a cookie, and MDN's cookie documentation is blunt about the default: cookie values are visible to and changeable by the end user, so a stolen or tampered session ID is a stolen identity, a criminal who gets your session cookie can present it and be you. The guards are cookie attributes, set when the cookie is created. Secure: only send it over HTTPS, never plaintext HTTP. HttpOnly: keep it away from JavaScript, so an injected script cannot read it. SameSite: control whether it rides along on cross-site requests, Strict or Lax meaning a request triggered from another site arrives without your session, which is the main defense against cross-site request forgery, the attack where another page makes your browser send a request you never intended. When you review generated auth, these three attributes on the session cookie are a five-second check with an outsized payoff.

07

Passwords: hashed, not encrypted, never stored

The rule that surprises people: a correct system cannot tell you your password, because it does not have it.

The rule that surprises peopleThe rule that surprises people, a correct system cannot tell you your password, because it does not have it.
What it stores is a hashWhat it stores is a hash, the output of a one-way function that turns the password into a fixed string that cannot be turned back.
Login hashes what you typed and compares hashes, matchLogin hashes what you typed and compares hashes, match, And you are in, without the password itself ever resting on disk.
OWASP's authentication guidanceOWASP's authentication guidance calls using the right cryptographic technique for storage critical, and points to a dedicated password-storage practice: the short version is that password hashing uses deliberately slow functions, bcrypt, Argon2, and their kin, because slowness is the defense, an attacker who steals the database must guess passwords one expensive try at a time rather than billions per second.
A salt, a random value mixed into each hashA salt, a random value mixed into each hash, defeats precomputed lookup tables.

Passwords: hashed, not encrypted, never stored

The rule that surprises people: a correct system cannot tell you your password, because it does not have it. What it stores is a hash, the output of a one-way function that turns the password into a fixed string that cannot be turned back. Login hashes what you typed and compares hashes; match, and you are in, without the password itself ever resting on disk. OWASP's authentication guidance calls using the right cryptographic technique for storage critical, and points to a dedicated password-storage practice: the short version is that password hashing uses deliberately slow functions, bcrypt, Argon2, and their kin, because slowness is the defense, an attacker who steals the database must guess passwords one expensive try at a time rather than billions per second. A salt, a random value mixed into each hash, defeats precomputed lookup tables. Two corollaries worth internalizing: any service that emails you your old password is storing it recoverably, a red flag; and encryption is the wrong word here, encrypted things can be decrypted by whoever holds the key, hashed things cannot be unhashed by anyone.

password typed at signupnever storedslow hash + salt storedbcrypt, Argon2: one-way by designlogin: hash the attempt, comparematch without ever keeping the passworda service that emails your old password is storing it: red flag

08

The login form is a security surface

The humble login form is where attackers probe, and OWASP's guidance reads like a list of ways to accidentally help them.

The humble login form is where attackers probeThe humble login form is where attackers probe, and OWASP's guidance reads like a list of ways to accidentally help them.
Error messages must be uniform"invalid user ID" tells an attacker the account exists and only the password is wrong, "invalid password" confirms the reverse, so the correct response is the merged one, "invalid user ID or password." Attempts must be throttled: unlimited guesses invite brute force, and OWASP's lockout guidance carries a non-obvious detail, the failed-login counter belongs on the account, not the source IP, because an attacker with many IP addresses walks straight past an IP-based counter.
Transport must be TLSTransport must be TLS, passwords cross the network encrypted or they do not cross safely.
None of these is exoticNone of these is exotic, and all three are visible in generated code if you look: the error strings, the rate limit, the redirect to HTTPS. uniform errors "invalid user ID or password" - never which one throttle on the account not the IP: attackers have many IPs TLS everywhere passwords cross the wire encrypted or not at all all three are visible in generated code if you look

The login form is a security surface

The humble login form is where attackers probe, and OWASP's guidance reads like a list of ways to accidentally help them. Error messages must be uniform: "invalid user ID" tells an attacker the account exists and only the password is wrong, "invalid password" confirms the reverse, so the correct response is the merged one, "invalid user ID or password." Attempts must be throttled: unlimited guesses invite brute force, and OWASP's lockout guidance carries a non-obvious detail, the failed-login counter belongs on the account, not the source IP, because an attacker with many IP addresses walks straight past an IP-based counter. Transport must be TLS, passwords cross the network encrypted or they do not cross safely. None of these is exotic, and all three are visible in generated code if you look: the error strings, the rate limit, the redirect to HTTPS.

uniform errors"invalid user ID or password" - never which onethrottle on the accountnot the IP: attackers have many IPsTLS everywherepasswords cross the wire encrypted or not at allall three are visible in generated code if you look

09

Password reset: the back door next to the front door

An attacker who cannot pick the lock tries the spare key, and the spare key is password reset.

OWASP's recovery guidanceOWASP's recovery guidance has one famous sentence pattern for a reason: the correct response to a reset request is "If that email address is in our database, we will send you an email to reset your password," because the eager version, "we just sent you a reset link," announces that the address has an account, and "this email doesn't exist" announces the reverse.
The mechanics deserve the same care as loginThe mechanics deserve the same care as login, reset tokens are random, single-use, and short-lived, a link that works forever is a permanent spare key; the token goes only to the address on file, never to an address typed at request time; and a successful reset ends other sessions, so whoever was in, in, is out.
Review generated reset flows with the same suspicion as loginReview generated reset flows with the same suspicion as login, Because attackers already do.

Password reset: the back door next to the front door

An attacker who cannot pick the lock tries the spare key, and the spare key is password reset. OWASP's recovery guidance has one famous sentence pattern for a reason: the correct response to a reset request is "If that email address is in our database, we will send you an email to reset your password," because the eager version, "we just sent you a reset link," announces that the address has an account, and "this email doesn't exist" announces the reverse. The mechanics deserve the same care as login: reset tokens are random, single-use, and short-lived, a link that works forever is a permanent spare key; the token goes only to the address on file, never to an address typed at request time; and a successful reset ends other sessions, so whoever was in, in, is out. Review generated reset flows with the same suspicion as login, because attackers already do.

10

MFA: the second proof

Multi-factor authentication asks for a second, different kind of proof after the password: a code from an authenticator app, a prompt on your phone, a hardware key.

Multi-factor authentication asks for a secondMulti-factor authentication asks for a second, different kind of proof after the password: a code from an authenticator app, a prompt on your phone, a hardware key.
The argument is arithmetic, not paranoia, passwords leakThrough breaches, reuse, and phishing, and a leaked password alone opens a single-factor account, while a leaked password plus a required second factor opens nothing the attacker has.
OWASP lists MFA first among its defenses against automated attacks
The practical notes for buildersThe practical notes for builders, authenticator-app codes beat SMS codes, texts can be intercepted and SIMs swapped, but any second factor beats none; recovery codes are the user's lifeline when the phone is gone, and they are passwords in every way that matters, store and treat them as such; and MFA protects the account's front door, not its sessions, which is why the next section's tokens matter too. factor one: the password something you know - and passwords leak factor two: app, prompt, or key something you have recovery codes passwords in every way that matters: store as such a leaked password plus a required second factor opens nothing

MFA: the second proof

Multi-factor authentication asks for a second, different kind of proof after the password: a code from an authenticator app, a prompt on your phone, a hardware key. The argument is arithmetic, not paranoia: passwords leak, through breaches, reuse, and phishing, and a leaked password alone opens a single-factor account, while a leaked password plus a required second factor opens nothing the attacker has. OWASP lists MFA first among its defenses against automated attacks. The practical notes for builders: authenticator-app codes beat SMS codes, texts can be intercepted and SIMs swapped, but any second factor beats none; recovery codes are the user's lifeline when the phone is gone, and they are passwords in every way that matters, store and treat them as such; and MFA protects the account's front door, not its sessions, which is why the next section's tokens matter too.

factor one: the passwordsomething you know - and passwords leakfactor two: app, prompt, or keysomething you haverecovery codespasswords in every way that matters: store assucha leaked password plus a required second factor opens nothing

11

Tokens and API keys: sessions for machines

Programs authenticate too, and the pattern rhymes with sessions.

Programs authenticate too and the pattern rhymes with sessions
An API key or access token is a randomAn API key or access token is a random, unguessable string presented with each request, like a session ID, but issued to a program rather than a browser.
The differences that matter, tokens often carry their own scopeThis key may read but not write, so a stolen read-only key cannot delete anything; tokens can expire on a schedule, bounding how long a leak is useful; and tokens are revocable individually, kill the leaked one without disturbing the rest.
When your builder wires a third-party API into your appThe key it asks for is exactly this object, and where it lands, server-side environment versus client bundle, decides whether your users' browsers are broadcasting it.

Tokens and API keys: sessions for machines

Programs authenticate too, and the pattern rhymes with sessions. An API key or access token is a random, unguessable string presented with each request, like a session ID, but issued to a program rather than a browser. The differences that matter: tokens often carry their own scope, this key may read but not write, so a stolen read-only key cannot delete anything; tokens can expire on a schedule, bounding how long a leak is useful; and tokens are revocable individually, kill the leaked one without disturbing the rest. The discipline is the connection-string rule from the database article: these are secrets, they live in environment config and secret stores, never in frontend code, never committed to a repository, and a leaked one gets rotated, not mourned. When your builder wires a third-party API into your app, the key it asks for is exactly this object, and where it lands, server-side environment versus client bundle, decides whether your users' browsers are broadcasting it.

12

What the OAuth provider actually returns

Worth one more layer of detail, because the review questions live here.

Worth one more layer of detailWorth one more layer of detail, because the review questions live here.
When the flow completesWhen the flow completes, your app receives tokens from the provider, and inside them, verifiable claims: the provider's name, the user's stable ID at that provider, usually their email, and an expiry.
Verifiable is the load-bearing wordVerifiable is the load-bearing word, the token is signed by the provider, and your app checks the signature against the provider's published keys, so a forged token fails.
The review checklist for generated OAuthThe review checklist for generated OAuth, the signature is verified, not just decoded, a decoded-but-unverified token is a costume, not an identity; the expiry is honored; and the stable provider ID, not the email string, is what links to your user record, because emails change and the ID does not.

What the OAuth provider actually returns

Worth one more layer of detail, because the review questions live here. When the flow completes, your app receives tokens from the provider, and inside them, verifiable claims: the provider's name, the user's stable ID at that provider, usually their email, and an expiry. Verifiable is the load-bearing word: the token is signed by the provider, and your app checks the signature against the provider's published keys, so a forged token fails. The review checklist for generated OAuth: the signature is verified, not just decoded, a decoded-but-unverified token is a costume, not an identity; the expiry is honored; and the stable provider ID, not the email string, is what links to your user record, because emails change and the ID does not.

13

OAuth: borrowing an identity

Sign in with Google, with GitHub, with Apple, is OAuth doing delegated authentication: instead of making a password for your app, the user asks a provider they already trust to vouch for them.

Sign in with Google, with GitHub, with AppleIs OAuth doing delegated authentication: instead of making a password for your app, the user asks a provider they already trust to vouch for them.
The flow at concept levelThe flow at concept level, your app sends the user to the provider; the provider authenticates them, with whatever strength it likes, phishing-resistant keys included; the provider returns a token to your app that says, verifiably, this is user so-and-so, and here is what they agreed to share.
Your app never sees their Google passwordYour app never sees their Google password, never stores a password at all for these users, and inherits the provider's security investment, which is why OWASP's cheat sheet includes OAuth among the protocols that authenticate without passwords.
The tradeoffs to knowThe tradeoffs to know, you now depend on the provider's availability and policies; account linking needs care, is the person with this Google account the same as the person with that email password, merge rules are a design decision, not an oversight; and the access the user grants your app is scoped, ask for the minimum. your app sends the user to the provider Google, GitHub, Apple provider authenticates them with its own security investment signed token returns verifiable identity, scoped access, no password seen verify the signature: a decoded-but-unverified token is a costume

OAuth: borrowing an identity

Sign in with Google, with GitHub, with Apple, is OAuth doing delegated authentication: instead of making a password for your app, the user asks a provider they already trust to vouch for them. The flow at concept level: your app sends the user to the provider; the provider authenticates them, with whatever strength it likes, phishing-resistant keys included; the provider returns a token to your app that says, verifiably, this is user so-and-so, and here is what they agreed to share. Your app never sees their Google password, never stores a password at all for these users, and inherits the provider's security investment, which is why OWASP's cheat sheet includes OAuth among the protocols that authenticate without passwords. The tradeoffs to know: you now depend on the provider's availability and policies; account linking needs care, is the person with this Google account the same as the person with that email password, merge rules are a design decision, not an oversight; and the access the user grants your app is scoped, ask for the minimum.

your app sends the user to the providerGoogle, GitHub, Appleprovider authenticates themwith its own security investmentsigned token returnsverifiable identity, scoped access, no passwordseenverify the signature: a decoded-but-unverified token is a costume

14

Magic links and one-time codes

Passwordless login inverts the reset flow into the login flow: type your email, receive a link or a code, click or enter it, you are in.

The security argument is real, nothing to reuseNothing to phish into a fake form, nothing to forget, and the proof rides on the email account, which for many people is their best-defended asset.
The honest accounting, you have moved the trust, not removed itEmail delivery, interception, and account takeover are now your front door; the links must expire quickly and work once, exactly like reset links, because they are reset links, one per login.
Codes shown on screen instead of links sent by email shift the trust again, to the device displaying them

Magic links and one-time codes

Passwordless login inverts the reset flow into the login flow: type your email, receive a link or a code, click or enter it, you are in. The security argument is real: nothing to reuse, nothing to phish into a fake form, nothing to forget, and the proof rides on the email account, which for many people is their best-defended asset. The honest accounting: you have moved the trust, not removed it, email delivery, interception, and account takeover are now your front door; the links must expire quickly and work once, exactly like reset links, because they are reset links, one per login. Codes shown on screen instead of links sent by email shift the trust again, to the device displaying them. Choose deliberately, and note what your builder chose, because its default becomes your policy.

15

Authorization: the second question, answered per request

Now the quieter door.

Every request that touches protected data answers two checksIs this session valid, authentication, and does this session's user get to touch this thing, authorization.
The second check decomposes into ownershipThe second check decomposes into ownership, this invoice belongs to user 7, and the session is user 7, and role, this action needs an admin, and user 7 is not one.
The rule with no exceptions, these checks run on the serverThe rule with no exceptions, these checks run on the server, On every request, against the server's own data.
Checks that live only in the frontend, hiding the buttonDisabling the route, are decoration: anyone can send the request the button would have sent.
When reviewing generated codeWhen reviewing generated code, the question that finds the bugs is never "is there a login check" but "where, exactly, does the server verify this user owns this record." session valid? authentication: yes, this is user 7 record belongs to user 7? authorization: the ownership condition both in the query invoice WHERE id=1043 AND user_id=7 hiding the button is decoration; the check lives on the server

Authorization: the second question, answered per request

Now the quieter door. Every request that touches protected data answers two checks: is this session valid, authentication, and does this session's user get to touch this thing, authorization. The second check decomposes into ownership, this invoice belongs to user 7, and the session is user 7, and role, this action needs an admin, and user 7 is not one. The rule with no exceptions: these checks run on the server, on every request, against the server's own data. Checks that live only in the frontend, hiding the button, disabling the route, are decoration: anyone can send the request the button would have sent. When reviewing generated code, the question that finds the bugs is never "is there a login check" but "where, exactly, does the server verify this user owns this record."

session valid?authentication: yes, this is user 7record belongs to user 7?authorization: the ownership conditionboth in the queryinvoice WHERE id=1043 AND user_id=7hiding the button is decoration; the check lives on the server

16

The ownership bug: the one to hunt

The classic authorization failure has a shape you can recognize in code and in URLs.

A page loads /invoices/1042A page loads /invoices/1042, the server checks the session is valid, fetches invoice 1042, renders it.
Change the URL to 1043, someone else's invoiceChange the URL to 1043, someone else's invoice, And it renders too, because nothing ever asked whether invoice 1043 belongs to this user.
The fix is always the same moveThe fix is always the same move, fetch the record with the user in the condition, the invoice where id is 1043 and user_id is the session's user, so a record that is not yours does not exist as far as the query is concerned, or check ownership explicitly after the fetch and refuse.
The login check is the part generators handle wellThe ownership check is the part to verify, and that gap is why this section exists, and why your review reads the data-fetching code, not the login screen. /invoices/1042 renders login check passed /invoices/1043 renders too nothing asked whose it is fix: user in the condition not yours = does not exist every manual test uses your own data, where the missing check passes

The ownership bug: the one to hunt

The classic authorization failure has a shape you can recognize in code and in URLs. A page loads /invoices/1042; the server checks the session is valid, fetches invoice 1042, renders it. Change the URL to 1043, someone else's invoice, and it renders too, because nothing ever asked whether invoice 1043 belongs to this user. Security people call this an insecure direct object reference; the working name is the ownership bug, and it is the difference between checking the door is locked and checking the key fits this room. The fix is always the same move: fetch the record with the user in the condition, the invoice where id is 1043 and user_id is the session's user, so a record that is not yours does not exist as far as the query is concerned, or check ownership explicitly after the fetch and refuse. The login check is the part generators handle well; the ownership check is the part to verify, and that gap is why this section exists, and why your review reads the data-fetching code, not the login screen.

/invoices/1042 renderslogin check passed/invoices/1043 renders toonothing asked whose it isfix: user in the conditionnot yours = does not existevery manual test uses your own data, where the missing check passes

17

Roles: when ownership is not enough

Some permissions are not about mine versus yours but about what kind of user you are: admins see everything, members see their team, guests read.

Roles are a column on the user, or a table of assignmentsPlus a check at each protected action: this route requires admin.
The disciplines that keep roles safe, deny by defaultAn action with no rule is closed, not open; the role check lives beside the ownership check, because an admin endpoint that only checks login is the ownership bug with a title; and role changes take effect on the server immediately, not whenever the user's cached copy of the app refreshes.
Start with the fewest roles that express your realityUser and admin covers a surprising distance, because every role you add multiplies the checks every route needs to get right.

Roles: when ownership is not enough

Some permissions are not about mine versus yours but about what kind of user you are: admins see everything, members see their team, guests read. Roles are a column on the user, or a table of assignments, plus a check at each protected action: this route requires admin. The disciplines that keep roles safe: deny by default, an action with no rule is closed, not open; the role check lives beside the ownership check, because an admin endpoint that only checks login is the ownership bug with a title; and role changes take effect on the server immediately, not whenever the user's cached copy of the app refreshes. Start with the fewest roles that express your reality, user and admin covers a surprising distance, because every role you add multiplies the checks every route needs to get right.

18

Sessions under attack: theft, fixation, and the guards

Because the session cookie is the identity, attackers aim at it, and the guards from the cookie section each answer a specific attack.

Because the session cookie is the identity, attackers aim at itBecause the session cookie is the identity, attackers aim at it, And the guards from the cookie section each answer a specific attack.
Theft by scriptTheft by script, an injected script reads the cookie and mails it out, HttpOnly makes it unreadable to scripts.
Theft by networkTheft by network, the cookie crosses a coffee-shop network in plaintext, Secure means it only ever travels encrypted.
Forgery by another siteForgery by another site, evil-page.com makes your browser POST to your bank with your cookie attached, SameSite means the cookie stays home on cross-site requests.
Fixation, the attacker hands you a session ID they knowYou log in, now they share your session, the defense is rotating the session ID at login, so the ID that existed before authentication dies the moment identity is proven.

Sessions under attack: theft, fixation, and the guards

Because the session cookie is the identity, attackers aim at it, and the guards from the cookie section each answer a specific attack. Theft by script: an injected script reads the cookie and mails it out, HttpOnly makes it unreadable to scripts. Theft by network: the cookie crosses a coffee-shop network in plaintext, Secure means it only ever travels encrypted. Forgery by another site: evil-page.com makes your browser POST to your bank with your cookie attached, SameSite means the cookie stays home on cross-site requests. Fixation: the attacker hands you a session ID they know, you log in, now they share your session, the defense is rotating the session ID at login, so the ID that existed before authentication dies the moment identity is proven. That last one is the check to run in generated code: a new session ID should be issued when a user logs in, and it is a one-line thing to verify.

Securenever travels plaintext HTTPHttpOnlyinvisible to injected scriptsSameSite=Lax or Strictstays home on cross-site requestsrotate at loginThe pre-login ID dies at authenticationfour attributes, five seconds to check, specific attacks answered

19

Testing auth as two users

The most productive auth test needs no tools: two browsers, two accounts.

The most productive auth test needs no tools, two browsersTwo accounts.
Take a URL from A's account, a document, an orderA settings page, and open it as B: anything of A's that renders for B is the ownership bug, caught in the act.
Then try the mutations, B submits A's form actionB calls A's export.
Then the sessions, A logs out, replay A's old cookieIt must be dead.
Change A's password A's other sessions must die

Testing auth as two users

The most productive auth test needs no tools: two browsers, two accounts. Log in as A in one, as B in the other. Take a URL from A's account, a document, an order, a settings page, and open it as B: anything of A's that renders for B is the ownership bug, caught in the act. Then try the mutations, B submits A's form action, B calls A's export. Then the sessions: A logs out, replay A's old cookie, it must be dead. Change A's password, A's other sessions must die. This drill finds what code review misses, because it tests the behavior, not the intention, and it takes ten minutes in an incognito window. Run it before launch and after any auth-touching change; it is the highest-yield hour in small-app security.

20

What the builder generates, and the ten-minute review

Ask an AI builder for accounts and it produces the stack: user and session tables, password hashing, login and registration routes, reset flow, middleware that checks sessions on protected routes.

Two, the session cookie Secure, HttpOnly, SameSite present
Three, login errors uniform and attempts throttledThree, login errors uniform and attempts throttled, With the counter on the account.
Four, reset flow, generic response, single-use short-lived tokenSessions ended on success.
Six, the data routesSix, the data routes, pick the one that fetches a user's record and find the ownership condition.

What the builder generates, and the ten-minute review

Ask an AI builder for accounts and it produces the stack: user and session tables, password hashing, login and registration routes, reset flow, middleware that checks sessions on protected routes. The review drill, in order. One, hashing: find where the password is stored and confirm a recognized password-hashing function does it, anything resembling plain storage or home-rolled hashing is a stop. Two, the session cookie: Secure, HttpOnly, SameSite present. Three, login errors uniform and attempts throttled, with the counter on the account. Four, reset flow: generic response, single-use short-lived token, sessions ended on success. Five, rotation: new session ID at login. Six, the data routes: pick the one that fetches a user's record and find the ownership condition. Six checks, ten minutes, and they cover the ground where generated auth goes wrong.

recognized password hashing?nothing plain, nothing home-rolledcookie guards + uniform errors +throttling?counter on the accountreset: generic, single-use, expiring?rotation at login?ownership condition in the fetch?The check that matters mostsix checks, ten minutes, the ground where generated auth slips

21

The middleware habit: one gate, not fifty

In code terms, the login check should live in one place, middleware or its equivalent, a gate every protected route passes through, rather than fifty hand-copied checks at the top of fifty handlers.

The structural reason, copied checks drift, one route forgetsOne route checks stale state, and the missing one is invisible until it matters.
The ownership check cannot centralize the same wayIt is per-resource, but it can be a habit with a template: fetch with the user in the condition, refuse on no row.
When you read generated routes, count the gatesOne authentication gate applied everywhere, and an ownership condition inside every data fetch.
Two patterns, visible at a glanceTwo patterns, visible at a glance, and their absence is just as visible.

The middleware habit: one gate, not fifty

In code terms, the login check should live in one place, middleware or its equivalent, a gate every protected route passes through, rather than fifty hand-copied checks at the top of fifty handlers. The structural reason: copied checks drift, one route forgets, one route checks stale state, and the missing one is invisible until it matters. The ownership check cannot centralize the same way, it is per-resource, but it can be a habit with a template: fetch with the user in the condition, refuse on no row. When you read generated routes, count the gates: one authentication gate applied everywhere, and an ownership condition inside every data fetch. Two patterns, visible at a glance, and their absence is just as visible.

22

Auth state in the UI: what the user sees

The interface side of auth is communication, and it has its own failure modes.

The interface side of auth is communicationThe interface side of auth is communication, and it has its own failure modes.
Show state honestly: logged in as who, on every page where it mattersShow state honestly: logged in as who, on every page where it matters, Because the person who does not know they are still logged in on a shared computer is a breach with a human face
Make logout findable and real, it must end the server sessionNot just hide the button.
Handle expiry gracefully, sessions endHandle expiry gracefully, sessions end, And the app that dumps a filled-out form on re-login teaches users to fear saving; re-authenticate and return them to their work.

Auth state in the UI: what the user sees

The interface side of auth is communication, and it has its own failure modes. Show state honestly: logged in as who, on every page where it matters, because the person who does not know they are still logged in on a shared computer is a breach with a human face. Make logout findable and real, it must end the server session, not just hide the button. Handle expiry gracefully: sessions end, and the app that dumps a filled-out form on re-login teaches users to fear saving; re-authenticate and return them to their work. And keep the security theater out of the interface: password meters that demand symbols but allow 'Password1!' train frustration, not safety, length is the lever that matters, and OWASP's strength guidance points the same way, toward length and breached-password screening rather than symbol gymnastics.

23

Sessions versus tokens, honestly

The industry argues about session cookies versus stateless tokens, usually JWTs, and the working summary fits in a paragraph.

A server-side session keeps state on the serverRevocation is instant, data stays private, the cost is a lookup per request.
A signed token carries its claims inside itself, user ID, expiryScopes, verified by signature rather than lookup: no server storage, easy to pass between services, and the cost is revocation, a token is valid until it expires no matter what you learn after issuing it, so token systems keep lifetimes short and add refresh machinery.
Neither is morally superior the failure mode is picking blindly
For a first app, server-side sessions are the legible choiceRevocation works the way you intuitively expect, logout really logs out, and there is one place where truth lives.

Sessions versus tokens, honestly

The industry argues about session cookies versus stateless tokens, usually JWTs, and the working summary fits in a paragraph. A server-side session keeps state on the server: revocation is instant, data stays private, the cost is a lookup per request. A signed token carries its claims inside itself, user ID, expiry, scopes, verified by signature rather than lookup: no server storage, easy to pass between services, and the cost is revocation, a token is valid until it expires no matter what you learn after issuing it, so token systems keep lifetimes short and add refresh machinery. Neither is morally superior; the failure mode is picking blindly. For a first app, server-side sessions are the legible choice: revocation works the way you intuitively expect, logout really logs out, and there is one place where truth lives.

24

Timing attacks and safe comparison

A subtle one worth knowing exists, even at concept level.

A subtle one worth knowing exists even at concept level
Comparing two secrets characterComparing two secrets character by character leaks information through time: the comparison stops at the first mismatch, so a guess with a longer correct prefix takes measurably longer, and an attacker can edge toward the secret one character at a time.
The defense is constant-time comparisonThe defense is constant-time comparison, functions that take the same time whether the inputs match or not, which is why OWASP recommends comparing password hashes with the safe comparison functions the language or framework provides rather than a hand-written equality check.
You will never write this comparison yourselfYou will never write this comparison yourself, the lesson is one level up: security-sensitive comparisons and parsing are library territory, because the wrong way to write them looks exactly like the right way.

Timing attacks and safe comparison

A subtle one worth knowing exists, even at concept level. Comparing two secrets character by character leaks information through time: the comparison stops at the first mismatch, so a guess with a longer correct prefix takes measurably longer, and an attacker can edge toward the secret one character at a time. The defense is constant-time comparison, functions that take the same time whether the inputs match or not, which is why OWASP recommends comparing password hashes with the safe comparison functions the language or framework provides rather than a hand-written equality check. You will never write this comparison yourself; the lesson is one level up: security-sensitive comparisons and parsing are library territory, because the wrong way to write them looks exactly like the right way.

25

Abuse beyond the account: the unauthenticated surface

Not every attack wants an account.

Open forms get abused for what they doOpen forms get abused for what they do, a contact form that sends email is a spam cannon; a signup that sends a welcome message is a harassment vector, type someone's address, they get mail from you; an endpoint that fetches a URL you give it is a proxy into your own network.
The defenses rhyme with everything aboveThe defenses rhyme with everything above, budgets on sends and fetches per identity and per IP, validation of what URLs and addresses are allowed, and proof-of-humanity checks, CAPTCHA and its successors, at the unauthenticated edges where budgets alone cannot tell a fan from a botnet.
Review the app's openReview the app's open surface with the question "what can a stranger make this do a thousand times," and budget accordingly.

Abuse beyond the account: the unauthenticated surface

Not every attack wants an account. Open forms get abused for what they do: a contact form that sends email is a spam cannon; a signup that sends a welcome message is a harassment vector, type someone's address, they get mail from you; an endpoint that fetches a URL you give it is a proxy into your own network. The defenses rhyme with everything above: budgets on sends and fetches per identity and per IP, validation of what URLs and addresses are allowed, and proof-of-humanity checks, CAPTCHA and its successors, at the unauthenticated edges where budgets alone cannot tell a fan from a botnet. Review the app's open surface with the question "what can a stranger make this do a thousand times," and budget accordingly.

26

Third-party auth libraries: standing on maintained ground

Auth is the last place to improvise, because the failure modes are silent, the code looks fine while being wrong.

Auth is the last place to improviseAuth is the last place to improvise, because the failure modes are silent, the code looks fine while being wrong.
This is where libraries and hosted auth earn their keepMaintained packages implement the hashing, the session rotation, the timing-safe comparisons, the reset token lifetimes, and they get patched when the world's understanding moves.
The review question for generated authThe review question for generated auth is therefore not only "is this correct" but "is this custom": every line of bespoke crypto, hand-rolled token formats, homemade comparison loops, is a line that must be justified against a maintained alternative.
The builder's instinctThe builder's instinct to write everything from scratch is fine for a hero section; auth plumbing is where you ask it to use the boring, maintained thing instead. custom auth code looks fine while being silently wrong maintained library or provider hashing, rotation, timing-safe compare, patched spend custom code on what makes you unique not on re-deriving session rotation auth plumbing is where you ask for the boring maintained thing

Third-party auth libraries: standing on maintained ground

Auth is the last place to improvise, because the failure modes are silent, the code looks fine while being wrong. This is where libraries and hosted auth earn their keep: maintained packages implement the hashing, the session rotation, the timing-safe comparisons, the reset token lifetimes, and they get patched when the world's understanding moves. The review question for generated auth is therefore not only "is this correct" but "is this custom": every line of bespoke crypto, hand-rolled token formats, homemade comparison loops, is a line that must be justified against a maintained alternative. The builder's instinct to write everything from scratch is fine for a hero section; auth plumbing is where you ask it to use the boring, maintained thing instead.

custom auth codelooks fine while being silently wrongmaintained library or providerhashing, rotation, timing-safe compare, patchedspend custom code on what makes you uniquenot on re-deriving session rotationauth plumbing is where you ask for the boring maintained thing

27

Session hygiene: expiry and cleanup

Sessions are rows too, and their lifecycle needs the same discipline as any table.

Sessions are rows tooSessions are rows too, and their lifecycle needs the same discipline as any table.
Every session has an expiry, absolute, and often idle-basedQuiet sessions die sooner than active ones.
Expired sessions get cleaned outExpired sessions get cleaned out, or the table grows forever and old tokens linger as forgotten doors.
Password changes and resets end all sessions for that userThe change-your-password-and-stay-logged-in-everywhere pattern leaves the attacker's session alive after you changed the locks.
Admin views of active sessions, the "log out other devices" listAre the same machinery exposed to the user.

Session hygiene: expiry and cleanup

Sessions are rows too, and their lifecycle needs the same discipline as any table. Every session has an expiry, absolute, and often idle-based, quiet sessions die sooner than active ones. Expired sessions get cleaned out, or the table grows forever and old tokens linger as forgotten doors. Password changes and resets end all sessions for that user, the change-your-password-and-stay-logged-in-everywhere pattern leaves the attacker's session alive after you changed the locks. Admin views of active sessions, the "log out other devices" list, are the same machinery exposed to the user. When the builder scaffolds sessions, these four, expiry, cleanup, global revocation, visibility, are the difference between a session system and a session pile.

28

Common attacks in plain language

Four attacks worth recognizing by mechanism, because the defenses make sense once the attacks do.

Four attacks worth recognizing by mechanismFour attacks worth recognizing by mechanism, because the defenses make sense once the attacks do.
Phishing, a lookalike page harvests what you typeDefenses are user-side vigilance plus phishing-resistant factors like security keys, and your side's job is never training users to type credentials into odd places.
Session theft: covered above answered by the cookie guards
Brute force, online guessing, answered by throttling and lockoutOffline guessing against a stolen database, answered by slow hashing, which is why the hashing choice matters even though your app never feels the difference.

Common attacks in plain language

Four attacks worth recognizing by mechanism, because the defenses make sense once the attacks do. Credential stuffing: passwords leaked from other sites get tried on yours, because people reuse passwords; defenses are throttling, MFA, and screening new passwords against known-breached lists. Phishing: a lookalike page harvests what you type; defenses are user-side vigilance plus phishing-resistant factors like security keys, and your side's job is never training users to type credentials into odd places. Session theft: covered above, answered by the cookie guards. Brute force: online guessing, answered by throttling and lockout; offline guessing against a stolen database, answered by slow hashing, which is why the hashing choice matters even though your app never feels the difference. Every defense in this article hangs on one of these four.

29

Auth and your database meet here

The database article's tools do double duty in auth.

The users table, email unique and lowercase-normalizedThe users table, email unique and lowercase-normalized, Or alice@ and Alice@ become two accounts; password hash column that no query ever selects into a page.
The sessions table, token or ID, user foreign key, expiryCreated-from metadata for the logs.
The ownership check is a WHERE clauseThe ownership check is a WHERE clause, which is why it belongs in the query, not in an if-statement three files away.
Cascades decide what deleting a user does to their dataCascades decide what deleting a user does to their data, And that is a legal and product question as much as a technical one.

Auth and your database meet here

The database article's tools do double duty in auth. The users table: email unique and lowercase-normalized, or alice@ and Alice@ become two accounts; password hash column that no query ever selects into a page. The sessions table: token or ID, user foreign key, expiry, created-from metadata for the logs. The ownership check is a WHERE clause, which is why it belongs in the query, not in an if-statement three files away. Cascades decide what deleting a user does to their data, and that is a legal and product question as much as a technical one. Auth is where the schema discipline pays its first dividend: constraints and transactions are what keep account state consistent when the reset email and the login attempt race each other.

users: email UNIQUE, lowercase-normalizedhash column never selected into a pagesessions: id, user key, expirycleanup and global revocationownership is a WHERE clauseconstraints keep account state consistentThe database article's discipline pays its first dividend here

30

When to outsource auth entirely

Sometimes the right auth code is none of yours.

Hosted identity providers run the whole stack, registrationHashing, MFA, reset, session management, OAuth brokering, as a service your app calls.
The case for, auth's failure modes are unforgivingThe maintenance never ends, and the provider's full-time job is exactly this.
The case against, a recurring cost that scales with usersA dependency whose outage is your outage, and user data flowing through a third party.
The honest default for a small team without security depthLeaning on a hosted provider or a heavily maintained library is not cowardice, it is triage, spend your custom-code budget where your app is unique, not on re-deriving session rotation. hand-rolled auth unforgiving failure modes, endless maintenance maintained library The machinery, in your codebase hosted provider The whole stack as a service, outage and cost included triage: lean on maintained ground where your app is not unique

When to outsource auth entirely

Sometimes the right auth code is none of yours. Hosted identity providers run the whole stack, registration, hashing, MFA, reset, session management, OAuth brokering, as a service your app calls. The case for: auth's failure modes are unforgiving, the maintenance never ends, and the provider's full-time job is exactly this. The case against: a recurring cost that scales with users, a dependency whose outage is your outage, and user data flowing through a third party. The honest default for a small team without security depth: leaning on a hosted provider or a heavily maintained library is not cowardice, it is triage, spend your custom-code budget where your app is unique, not on re-deriving session rotation.

hand-rolled authunforgiving failure modes, endless maintenancemaintained libraryThe machinery, in your codebasehosted providerThe whole stack as a service, outage and costincludedtriage: lean on maintained ground where your app is not unique

31

A worked review: generated login, line by line

Run the drill once on a typical generated flow.

Registration, the handler lowercases the emailChecks it against the users table's UNIQUE constraint, hashes the password with a recognized slow function, good, the bouncer does uniqueness, the hash never rests as plaintext.
Login, finds the userCompares hashes with the library's verify function, and on failure returns one message whether the email or the password was wrong, good; the failed counter increments on the account row, not the IP, good.
Success, a new session ID is generated, the old one discardedThe cookie set with Secure, HttpOnly, SameSite=Lax, good.
The invoice route fetches with user_id in the condition, good

A worked review: generated login, line by line

Run the drill once on a typical generated flow. Registration: the handler lowercases the email, checks it against the users table's UNIQUE constraint, hashes the password with a recognized slow function, good, the bouncer does uniqueness, the hash never rests as plaintext. Login: finds the user, compares hashes with the library's verify function, and on failure returns one message whether the email or the password was wrong, good; the failed counter increments on the account row, not the IP, good. Success: a new session ID is generated, the old one discarded, the cookie set with Secure, HttpOnly, SameSite=Lax, good. The invoice route: fetches with user_id in the condition, good. The reset route: single generic response, token expires in an hour, works once, ends other sessions, good. Six sentences, and you now know more about your app's front door than most people who own one.

registration: hash + UNIQUE emailThe bouncer owns uniquenesslogin: verify, uniform error, accountcounternew session ID on successroutes: user in the conditionreset: generic, expiring, single-usesix sentences, and you know your front door

32

Common confusions, untangled

The pairs that blur.

Authentication versus authorizationAuthentication versus authorization, who you are versus what you may do; the login screen versus the ownership check.
Hashing versus encryption, one-way versus reversiblePasswords get the first, data at rest gets the second.
Session versus token, server-remembered versus self-carriedBoth are strings in a cookie or header, the difference is where truth lives.
Cookie versus session, the cookie is the envelopeThe session is the account record it points at; clearing cookies strands your side, deleting the session strands theirs.
Login versus signup, registration is not authenticationIt is identity creation, and it needs its own anti-abuse budget.

Common confusions, untangled

The pairs that blur. Authentication versus authorization: who you are versus what you may do; the login screen versus the ownership check. Hashing versus encryption: one-way versus reversible; passwords get the first, data at rest gets the second. Session versus token: server-remembered versus self-carried; both are strings in a cookie or header, the difference is where truth lives. Cookie versus session: the cookie is the envelope, the session is the account record it points at; clearing cookies strands your side, deleting the session strands theirs. Login versus signup: registration is not authentication, it is identity creation, and it needs its own anti-abuse budget. And OAuth the sign-in versus OAuth the integration: "Sign in with Google" proves identity; "connect your Google Drive" grants your app ongoing access to their data, related machinery, different stakes, and the scopes you request are the contract.

33

Vocabulary that makes auth legible

The terms pinned to their ideas.

Session: the server-side record that keeps you logged in
Hashing: the one-way function that stores passwords without storing them
Salt: the random value that makes each hash unique
OAuth: delegating identity to a provider that already knows you
Token or API key, a session for a programToken or API key, a session for a program, With scopes and expiry.

Vocabulary that makes auth legible

The terms pinned to their ideas. Authentication: proving who you are. Authorization: proving you may do this. Session: the server-side record that keeps you logged in. Session cookie: the transport for the session ID, guarded by Secure, HttpOnly, SameSite. Hashing: the one-way function that stores passwords without storing them. Salt: the random value that makes each hash unique. MFA: a second, different kind of proof. OAuth: delegating identity to a provider that already knows you. Token or API key: a session for a program, with scopes and expiry. Ownership check: the WHERE clause that makes other people's data not exist for you. Role: a permission class checked at the action. Rotation: replacing an ID or secret so the old one dies.

34

Frequently asked questions

If the app has nothing per-user, no saved work, no private data, no actions attributed to anyone, you may not. The moment anything is mine-versus-yours, you do, and retrofitting auth onto data that was modeled without owners is one of the more painful schema surgeries, so decide early.

For many apps, yes, the provider handles passwords, MFAFor many apps, yes, the provider handles passwords, MFA, And recovery, and you store no credentials at all.
The gaps to fill are account linking rulesThe gaps to fill are account linking rules, what happens when one person has two providers, and the dependency itself, your login is down when theirs is.
Many apps offer both OAuth and email for exactly that reason
Because encryption is reversible by design, anyone with the keyBecause encryption is reversible by design, anyone with the key, Including an attacker who steals both the database and the key from the same server, gets every password back.
Hashing is one-way, there is nothing to reverseHashing is one-way, there is nothing to reverse, So a stolen hash database forces slow guessing instead of instant recovery.

Frequently asked questions

Do I need auth at all for my app?

If the app has nothing per-user, no saved work, no private data, no actions attributed to anyone, you may not. The moment anything is mine-versus-yours, you do, and retrofitting auth onto data that was modeled without owners is one of the more painful schema surgeries, so decide early.

Is Sign in with Google enough on its own?

For many apps, yes: the provider handles passwords, MFA, and recovery, and you store no credentials at all. The gaps to fill are account linking rules, what happens when one person has two providers, and the dependency itself, your login is down when theirs is. Many apps offer both OAuth and email for exactly that reason.

Why can't I just encrypt the passwords?

Because encryption is reversible by design: anyone with the key, including an attacker who steals both the database and the key from the same server, gets every password back. Hashing is one-way; there is nothing to reverse, so a stolen hash database forces slow guessing instead of instant recovery. That asymmetry is the entire point.

Do I need CAPTCHA from day one?

Only where abuse is cheap and costly: public signup, public forms, anything that sends email or SMS. Behind a login, budgets and throttles usually do the work. Add friction where the abuse actually arrives, and prefer the least annoying proof that stops it, every hurdle at signup is measured in lost real users too.

What happens to auth when I add team accounts?

Teams turn ownership into membership: the question changes from "is this yours" to "do you belong to the group that owns this, and what is your role in it." Model it explicitly, a memberships table joining users to teams with roles, and make every check walk through membership rather than a user-id-on-the-record shortcut, because the shortcut breaks the day a record has many owners.

Are passkeys worth it yet?

Passkeys are the direction the industry is pushing: a key pair on the user's device, the public half registered with your app, the private half unlocked by the device's own biometric or PIN, nothing typed, nothing to phish into a fake page, nothing reusable across sites. Support across modern devices is broad and improving. For a builder the practical path is incremental: passkeys as an option alongside whatever you have, through a library or provider that implements the ceremony, rather than hand-rolled.

My builder wants to store auth tokens in localStorage. Is that fine?

localStorage is readable by any script that runs on the page, which is exactly the script-injection hole HttpOnly exists to close. Tokens there are one injected script away from exfiltration. The cookie with HttpOnly keeps the token out of script reach entirely; if the architecture forces tokens into web storage, the injected-script defense has to come from somewhere else, and that is a tradeoff to make knowingly, not by default.

How long should a session last?

Long enough that users are not constantly re-authenticating, short enough that a stolen cookie expires before it is useful, and the balance shifts with what the app protects: a reading app can offer weeks, a payment console should offer hours and re-authentication for the sensitive moves, which is the pattern OWASP recommends for sensitive features. Whatever you choose, revocation must work, logout ends it, admin ends it, password change ends it.

What is the single most likely bug in generated auth?

The missing ownership check: the server verifies you are logged in, then fetches whatever ID the request named, without asking whether it is yours. It hides because every manual test uses your own data, where the check you forgot is one you would have passed anyway. Test as two users and try to read each other's records; nothing else surfaces it faster.

Should users pick their own usernames?

Email-as-identity is the simpler default: one less thing to remember, one less namespace to police. OWASP's guidance adds a subtlety worth knowing, usernames and user IDs are not secrets, so never treat them as a security layer; the password and the factors are the secrets. Whatever identifies the user publicly should be assumed known.

35

The bottom line

Auth holds together once the two questions stay separate: authentication proves identity, once and then by session; authorization re-proves permission on every request, server-side, with the user in the query.

Around that spine sit a dozen small, knowable guardsHashed passwords with slow functions, uniform errors, throttled attempts, single-use reset links, guarded cookies, rotated session IDs, scoped tokens.
None of it is exotic, all of it is checkableNone of it is exotic, all of it is checkable, And the ten-minute drill catches the places generated code cuts the corner.
When the checks stop being enoughWhen the checks stop being enough, when the threat model includes real money or regulated data, that is one of the lines the AI builder versus hiring article draws, and the security-basics article widens the lens beyond auth.

The bottom line

Auth holds together once the two questions stay separate: authentication proves identity, once and then by session; authorization re-proves permission on every request, server-side, with the user in the query. Around that spine sit a dozen small, knowable guards: hashed passwords with slow functions, uniform errors, throttled attempts, single-use reset links, guarded cookies, rotated session IDs, scoped tokens. None of it is exotic, all of it is checkable, and the ten-minute drill catches the places generated code cuts the corner. When the checks stop being enough, when the threat model includes real money or regulated data, that is one of the lines the AI builder versus hiring article draws, and the security-basics article widens the lens beyond auth.

36

Sources for the factual claims

The review drills and build-versus-outsource judgment are editorial; security needs vary with what your app protects, and this article is engineering guidance, not legal or compliance advice.

MDN - HTTP authenticationMDN - HTTP authentication The protocol-level challenge and response framework: 401 and WWW-Authenticate, the Authorization header, and the Basic scheme.
Grounds the stateless-foundation sectionGrounds the stateless-foundation section.
OWASP Cheat Sheet SeriesOWASP Cheat Sheet Series - Authentication Cheat Sheet The defensive practices quoted and paraphrased throughout: uniform error messages (the "Invalid user ID or password" and "If that email address is in our database" examples), account-based throttling rather than IP-based, secure password storage and safe comparison functions, MFA, re-authentication for sensitive features, and logging.
Grounds the login reset, MFA and logging sections
MDN - Using HTTPMDN - Using HTTP cookies cookie visibility by default and the guards: Secure, HttpOnly, SameSite (Strict, Lax, None) and what SameSite protects against.

Sources for the factual claims

The review drills and build-versus-outsource judgment are editorial; security needs vary with what your app protects, and this article is engineering guidance, not legal or compliance advice.

  1. MDN - HTTP authentication
    The protocol-level challenge and response framework: 401 and WWW-Authenticate, the Authorization header, and the Basic scheme. Grounds the stateless-foundation section.
  2. OWASP Cheat Sheet Series - Authentication Cheat Sheet
    The defensive practices quoted and paraphrased throughout: uniform error messages (the "Invalid user ID or password" and "If that email address is in our database" examples), account-based throttling rather than IP-based, secure password storage and safe comparison functions, MFA, re-authentication for sensitive features, and logging. Grounds the login, reset, MFA and logging sections.
  3. MDN - Using HTTP cookies
    cookie visibility by default and the guards: Secure, HttpOnly, SameSite (Strict, Lax, None) and what SameSite protects against. Grounds the cookie and session-theft sections.
A wooden desk with glasses, a coffee cup, a plant and the edge of a laptop, banner image on the Auth explained for app builders page

Keep reading, or try a tool.

Long-form guides on building, automating and AI computing.