Passwords and Signing In

Store passwords the only safe way, as hashes, then build sign-up and sign-in. You'll hand out tokens (JWTs) that prove who someone is, look inside one to see what it can't hide, and learn when session cookies are the better choice. Then you'll build a study group's sign-in.

Updated

Passwords

  1. Storing Passwords Safely: Hashing with pwdlib (Journeyman): An API never stores a password, plain or encrypted, only a slow, salted, one-way hash of it made with Argon2 through pwdlib's PasswordHash.recommended(), and it checks each sign-in attempt with verify.
  2. Sign-Up and Sign-In Routes (Journeyman): A students table with a password_hash column and a UNIQUE email holds the accounts, a sign-up route hashes the password and answers 201 with the new student or 409 for a used email, a response model keeps the hash out of every answer, and sign-in answers a wrong email and a wrong password with the same 401.

Staying Signed In

  1. Tokens: Signing In with a JWT (Journeyman): After a sign-in, an API hands out a JWT, a signed token in three parts that PyJWT makes with jwt.encode and an exp claim and checks with jwt.decode, at POST /auth/token with the OAuth2 password form so the docs page's Authorize button works, and the caller sends it back in an Authorization header with every request.
  2. Sessions and Cookies, and When They Fit Better (Journeyman): A session signs a user in with a random id from secrets.token_urlsafe, kept in a sessions table and sent in an HttpOnly, Secure, SameSite cookie, so signing out deletes a row and takes effect at once, which suits one website on one server better than a token that stays valid until it expires.

Exercise: Study Group Sign-In

  1. Exercise: Study Group Sign-In (Journeyman): Give a study group's FastAPI app accounts it can trust, with passwords saved only as Argon2 hashes from pwdlib, a sign-up that answers 201 or 409 for a used email, a sign-in at POST /auth/token that hands out a PyJWT token good for an hour or one vague 401, and a /me route that reads the token, all tested on a throwaway SQLite database.