Skip to content
Tutorials Center
My learning

Topics

Lesson 115 of 147 ยท Web and Networking

Authentication, Sessions and JWT in Go

Build login in Go with the standard library - hash passwords with PBKDF2, keep users signed in with secure cookie sessions, issue and verify HS256 JWTs, and protect routes with middleware.

Almost every web application has to answer one question on every request: who is calling? That is authentication. It has three separate jobs. First, you must store passwords so that a stolen database does not give away the passwords. Second, after a successful login you need a way to recognize the same user on later requests, because HTTP itself remembers nothing. Third, you must check that proof on every protected route.

There are two popular answers to the second job. A session keeps the user's state on the server and gives the browser an unguessable ID in a cookie. A token such as a JWT (JSON Web Token) carries the user's claims inside a signed string, so the server can verify it without looking anything up. This lesson builds both with the standard library: password hashing, a cookie session store, a hand-written HS256 JWT signer and verifier, and middleware that guards routes. You already know middleware and the crypto basics; this lesson puts them to work.

Security code is easy to get subtly wrong. The code here is meant for learning how the pieces fit together. In production, prefer well-reviewed libraries for tokens (for example golang-jwt/jwt), use x/crypto bcrypt or argon2 for passwords where you can add a dependency, and have your design reviewed.

Storing passwords

Never store a password, and never store a plain fast hash of it (such as SHA-256). Attackers who steal the database can try billions of guesses per second against a fast hash. A password hash function is deliberately slow and uses a random salt per user, so identical passwords produce different stored values and precomputed tables are useless.

The standard library has crypto/pbkdf2 (since Go 1.24). Together with crypto/rand for the salt and crypto/subtle for comparing, it is enough for a sound scheme. Store the algorithm parameters together with the result, so you can raise the cost later and still verify old hashes.

Go Salted PBKDF2 password hashes

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

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

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

Some design details matter. The salt is random and stored beside the hash; it is not secret. subtle.ConstantTimeCompare avoids leaking, through timing, how many leading bytes matched. The iteration count is part of the stored string, so when hardware gets faster you raise iterations for new passwords, and rehash old ones the next time a user logs in. Because every login now costs a few hundred milliseconds of CPU, protect the login route with a rate limiter, otherwise it is an easy way to exhaust your servers.

Two more rules. When login fails, say "wrong email or password" and nothing more, so attackers cannot find out which emails exist. And never write passwords or tokens to logs.

Sessions with cookies

After the password check, the server creates a session: a record on the server (user ID, expiry) filed under a long random ID. The browser receives only the ID, in a cookie, and sends it back automatically with every request.

sequenceDiagram
    participant B as Browser
    participant S as Server
    participant D as Session store
    B->>S: POST /login (email, password)
    S->>S: Check the password hash
    S->>D: Save session id -> user, expiry
    S->>B: Set-Cookie: sid=random (HttpOnly, Secure)
    B->>S: GET /me (Cookie: sid=random)
    S->>D: Look up the id
    D->>S: user alice
    S->>B: 200 hello alice

A cookie session: the browser holds only a random ID, and the server holds the data.

The cookie's attributes are your first line of defense:

Attribute Effect
HttpOnly JavaScript cannot read the cookie, so an XSS bug cannot steal the session ID.
Secure The browser sends it only over HTTPS (see TLS and HTTPS).
SameSite=Lax The browser does not send it on cross-site POST requests, which blocks most CSRF attacks.
Path=/, MaxAge Scope and lifetime. Use a finite lifetime.

The ID must come from crypto/rand (never math/rand) and should have at least 128 bits, here 256. Create a new ID at every login so that an attacker cannot plant a known ID before the user signs in (a session fixation attack).

This server uses a TLS test server, so the Secure cookie really is sent, and a cookiejar plays the browser:

Go A cookie session: login, protected route, logout

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

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

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

Study the pieces. require is ordinary middleware: it reads the cookie, looks the session up, and passes the user to the next handler through the context with a private key type. Logout deletes the server-side record, so the old cookie is useless even if someone copied it, which is a real advantage of sessions: you can end one at any time. The cross-site attempt is stopped by http.CrossOriginProtection before it reaches your handlers; it is a modern CSRF defense that looks at the browser's Sec-Fetch-Site and Origin headers, and it lets non-browser clients (which send neither) through. For sensitive apps you can combine it with SameSite cookies, as here.

In a real application the store lives in Redis or a database, not in memory, so sessions survive restarts and are shared across several servers (see Redis and NoSQL). Always bound the lifetime and delete expired sessions.

JSON Web Tokens

A JWT has three dot-separated parts, each Base64URL-encoded: a header (the algorithm), a payload of claims (who the token is about and when it expires), and a signature. With the HS256 algorithm the signature is an HMAC-SHA256 over header.payload using a secret that only your servers know. Anyone can read a JWT, so never put secrets in it, but nobody can change it without the key.

flowchart LR
    H["header<br/>alg: HS256"] --> J(("header.payload"))
    P["payload<br/>sub, role, exp"] --> J
    J --> M["HMAC-SHA256<br/>with secret key"]
    M --> S["signature"]
    J --> T["token = header.payload.signature"]
    S --> T

How an HS256 token is built. To verify it, the server recomputes the signature and compares.

Signing needs only crypto/hmac, encoding/json and encoding/base64. The verifying side is where the security lives, and there are classic mistakes to avoid. Always pin the algorithm you expect instead of trusting the header (the infamous alg: none attack sends an unsigned token and hopes the server accepts it). Compare signatures with hmac.Equal. Always check the expiry. And do not leak details about why a token failed to the client.

Go Signing and verifying HS256 tokens

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

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

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

The token is shorter than you may expect because we use only a handful of claims. The standard names (the "registered claims") are iss (issuer), sub (subject, usually the user ID), aud (audience), exp (expiry), nbf (not before), iat (issued at) and jti (a unique ID). A complete implementation also checks iss and aud, allows a few seconds of clock skew, and supports key rotation through a kid header. That growing list of details is the best reason to use a library in production rather than your own code.

Protecting routes with a token

Clients send the token in an Authorization: Bearer <token> header. A middleware extracts it, verifies it and puts the claims in the request context. A second layer, authorization, then checks the role. This example calls the handlers directly with httptest, so no network is needed.

Go Bearer-token middleware with a role check

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

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

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

Two status codes do two different jobs: 401 Unauthorized means "I do not know who you are" (missing or invalid credentials), and 403 Forbidden means "I know who you are, and you may not do this". The WWW-Authenticate header on a 401 tells clients which scheme to use.

Sessions or JWTs?

Neither is "better"; they trade different things.

Server session JWT
State On the server (store lookup per request) In the token (no lookup)
Revoking one user Delete the record: instant Hard: valid until it expires
Size on the wire Tiny ID A few hundred bytes
Fits best Browser apps on one site APIs, mobile apps, service-to-service calls
Main risks Store becomes a dependency Stolen tokens live until expiry; mistakes in verification

Because a JWT cannot be revoked easily, keep access tokens short-lived (minutes) and pair them with a longer-lived refresh token that you do store on the server and can revoke. Do not keep JWTs in localStorage where any script on the page can read them; for browser apps a HttpOnly cookie is safer, and then you again need CSRF protection. When in doubt, a plain server session in a cookie is the simplest sound choice for a website.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is storing sha256(password) a poor way to protect user passwords?

    Password hashing needs to be slow and salted. A fast unsalted hash can be attacked with huge guess rates and precomputed tables. Use PBKDF2, bcrypt, scrypt or argon2 with a per-user salt.
  2. 2. Which cookie attribute stops JavaScript running on your page from reading the session ID?

    HttpOnly hides the cookie from document.cookie, so an XSS bug cannot copy the session ID. Secure limits it to HTTPS and SameSite limits cross-site sending, but neither hides it from scripts.
  3. 3. What makes the alg: none attack work against a careless JWT verifier?

    If the header decides how to verify, an attacker can ask for no verification. Pin the expected algorithm in the server code.
  4. 4. A user presents a valid token, but the route needs the admin role and the token says "user". Which status fits best?

    The caller is authenticated, so 401 would be wrong. 403 means the identity is known but lacks permission.
  5. 5. What is the main practical drawback of a stateless JWT compared with a server-side session?

    A server session ends the moment you delete its record. A JWT is valid until it expires unless you add a denylist, which brings back server state. That is why access tokens are short-lived.

Summary

  • Hash passwords with a slow, salted function (crypto/pbkdf2 in the standard library, bcrypt or argon2 from x/crypto), store the parameters with the hash and compare with subtle.ConstantTimeCompare.
  • A session stores state on the server and gives the browser a random ID in a cookie with HttpOnly, Secure and SameSite. Generate IDs with crypto/rand, issue a fresh one at login and delete it at logout.
  • http.CrossOriginProtection (Go 1.25+) rejects cross-site browser writes; keep SameSite cookies too.
  • A JWT is header.payload.signature. HS256 signs with HMAC-SHA256; readable by anyone, changeable by no one without the key. Pin the algorithm, use hmac.Equal, check exp (and iss/aud).
  • Authentication middleware verifies the credential and stores the identity in the request context; authorization decides what that identity may do. Use 401 for unknown callers and 403 for forbidden ones.
  • Keep access tokens short-lived and prefer a library for JWTs in production.

Next: Databases with database/sql