Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท Authentication and Security

Password Hashing and Cookie Sessions in Gin

Store passwords safely with bcrypt, build register and login routes in Gin, keep users signed in with secure session cookies, and protect routes with an auth middleware.

Authentication answers "who is this?", authorization answers "what may they do?". The classic browser flow has two parts: when a user registers you store a password hash, and when they log in you check the password and give the browser a session cookie that identifies them on later requests. Get either part wrong and your users are at risk, so this lesson sticks to well-tested building blocks.

Gin and golang.org/x/crypto/bcrypt are not available in the in-page runner, so their code is shown read-only. The runnable examples rebuild the ideas with the standard library: a salted, slow hash from crypto/pbkdf2, constant-time comparison, random session IDs and a cookie-based middleware. For token-based API auth, continue with JWT Authentication.

Never store passwords, store hashes

If your database leaks (it happens to careful teams too), plain-text passwords expose every user, because people reuse them. A hash is a one-way function: you can compute it from the password, but not the other way. Fast hashes such as SHA-256 are the wrong tool, since attackers can try billions of guesses per second. Use an algorithm that is deliberately slow and salted (a random value stored with the hash, so equal passwords give different hashes):

  • bcrypt: the long-time default, one function call, salt included in the output.
  • argon2id: the current recommendation, memory-hard; available as golang.org/x/crypto/argon2.
  • scrypt and PBKDF2: acceptable when parameters are strong.
Go
import "golang.org/x/crypto/bcrypt"

hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
// store string(hash), e.g. "$2a$10$N9qo8uLOickgx2ZMRZoMy..."

err = bcrypt.CompareHashAndPassword(storedHash, []byte(attempt))
if err != nil { /* wrong password */ }

bcrypt has a 72-byte input limit, so reject longer passwords or pre-hash them. Choose the cost so that one hash takes roughly 50 to 250 ms on your server.

Salted slow hashing, runnable

The standard library has PBKDF2 (crypto/pbkdf2). This example is a stand-in for bcrypt: same shape (random salt, slow function, encoded result, constant-time check). Run it and notice that hashing the same password twice gives different strings.

Go Salted, slow 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.

The comparison uses subtle.ConstantTimeCompare, which takes the same time wherever the first difference is. A plain == can leak information through timing. (bcrypt's CompareHashAndPassword already does this for you.)

Register and login handlers

Go
func (s *Server) register(c *gin.Context) {
	var in struct {
		Email    string `json:"email" binding:"required,email"`
		Password string `json:"password" binding:"required,min=10,max=72"`
	}
	if err := c.ShouldBindJSON(&in); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	hash, _ := bcrypt.GenerateFromPassword([]byte(in.Password), bcrypt.DefaultCost)
	user := User{Email: strings.ToLower(in.Email), PasswordHash: string(hash)}
	if err := s.db.Create(&user).Error; err != nil {
		c.JSON(http.StatusConflict, gin.H{"error": "email already registered"})
		return
	}
	c.JSON(http.StatusCreated, gin.H{"id": user.ID})
}

func (s *Server) login(c *gin.Context) {
	// ...bind email and password...
	var user User
	err := s.db.Where("email = ?", strings.ToLower(in.Email)).First(&user).Error
	if err != nil || bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(in.Password)) != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid email or password"})
		return
	}
	// create the session here
}

Notice that "unknown email" and "wrong password" give the same answer, so attackers cannot discover which emails have accounts. (Real sites still need a rate limit on login: see Rate Limiting and Input Safety.) Tag the hash field json:"-" so it can never appear in a response.

Sessions: remembering the user

HTTP is stateless. After a successful login the server creates a session: a random, unguessable ID stored server-side (memory, Redis or a database) together with the user's identity, and sends the ID to the browser in a cookie. Every later request carries the cookie, and the server looks the ID up.

sequenceDiagram
    participant B as Browser
    participant S as Gin server
    participant R as Session store
    B->>S: POST /login (email, password)
    S->>S: check password hash
    S->>R: save session id -> user 42
    S-->>B: 204 + Set-Cookie sid (HttpOnly, Secure)
    B->>S: GET /me (Cookie: sid=random)
    S->>R: look up sid
    R-->>S: user 42
    S-->>B: 200 {"id":42}

The cookie holds only a random ID; the data lives on the server.

The cookie flags are part of your security:

  • HttpOnly: JavaScript cannot read it, so an XSS bug cannot steal the session.
  • Secure: sent only over HTTPS.
  • SameSite=Lax (or Strict): not sent on most cross-site requests, which blocks much CSRF (see CORS, CSRF and Security Headers).
  • A sensible Max-Age and a server-side expiry.

In Gin you set it with c.SetSameSite(http.SameSiteLaxMode) and c.SetCookie("sid", id, 3600*24, "/", "", true, true), or use github.com/gin-contrib/sessions, which provides stores for cookies, Redis and databases.

A working session flow, runnable

This stand-in implements login, a session store, a cookie and an RequireLogin middleware with plain net/http. The Gin version has the same four parts.

Go Login, session cookie and a protected route

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 demo keeps a clear-text password so the example stays short. Your real handler compares hashes as shown above.)

Logout and session hygiene

Logout deletes the server-side session and expires the cookie (c.SetCookie("sid", "", -1, ...)). Create a new session ID at login (never reuse one from before login, to prevent session fixation), expire idle sessions, and delete all of a user's sessions when they change their password.

Common mistakes

  • Hashing with MD5, SHA-1 or plain SHA-256.
  • Comparing hashes or tokens with ==.
  • Telling the visitor whether the email or the password was wrong.
  • Cookies without HttpOnly, Secure or SameSite.
  • Putting the whole user record (or role) in a client-readable cookie that the server trusts without a signature.
  • Logging passwords, even in failed-login messages.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is SHA-256 alone a poor way to store passwords?

    Password hashing should be slow and salted. Use bcrypt, argon2id, scrypt or PBKDF2 with strong parameters.
  2. 2. What is the purpose of a salt?

    A random per-password salt means every hash must be attacked separately.
  3. 3. Which cookie flag stops JavaScript from reading the session cookie?

    HttpOnly hides the cookie from document.cookie, limiting the damage of an XSS bug.
  4. 4. A login fails. What should the response say?

    One generic message prevents attackers from finding out which emails are registered.

Summary

  • Store only slow, salted hashes (bcrypt or argon2id); compare in constant time.
  • Return identical errors for unknown user and wrong password, and rate-limit login.
  • A session is a random ID in an HttpOnly, Secure, SameSite cookie that maps to server-side data.
  • Issue a fresh session ID at login and destroy it at logout; guard routes with a middleware.

Next: JWT Authentication