Start learning free

LESSON 84 OF 173 · BACKEND: USERS AND SECURITY

401 or 403? in Go

Practice

The shop now hands out keys to its staff too, for other jobs later. Adding products stays the owner's job. So a refused request can mean two different things, and HTTP has a status for each.

401 Unauthorized means "I don't know who you are": the key is missing, or it isn't one of the shop's keys. 403 Forbidden means "I know who you are, and you may not do this": the key is real, but its role isn't allowed. After a 401 a client should send a valid key; after a 403, trying again won't help.

A map can link each valid key to its role. Looking a key up can give two values: the stored value, and a bool that says whether the key was there. A missing key gives the empty text "" and false, never an error. Here with made-up keys for a music app:

var plans = map[string]string{"free-key-1": "free", "pro-key-2": "pro"}

plan, ok := plans["pro-key-2"]
fmt.Println(plan, ok)       // pro true
plan, ok = plans[""]
fmt.Println(plan == "", ok) // true false

These are the requests your code must answer:

POST /products  {"name": "Vase", "price": 18}  (no key)                    →  401  {"error": "Missing or unknown key"}
POST /products  {"name": "Vase", "price": 18}  X-Admin-Key: let-me-in      →  401  {"error": "Missing or unknown key"}
POST /products  {"name": "Vase", "price": 18}  X-Admin-Key: staff-key-456  →  403  {"error": "Admins only"}
POST /products  {"name": "Vase", "price": 18}  X-Admin-Key: admin-key-123  →  201  {"id": 9, "name": "Vase", "price": 18}
GET /products/10  →  404  {"error": "Product not found"}

Your task: replace adminKey with a map apiKeys that links "admin-key-123" to "admin" and "staff-key-456" to "staff". In the POST /products handler, look the key up into role, ok, answer 401 when it isn't found, then 403 with {"error": "Admins only"} when its role isn't "admin".


Assignment
Follow the Coding Tutorial to tell an unknown caller (401) from a known caller who isn't allowed (403).


Hint
Keep the order: 401 first, then 403. A missing key gives the role "" without any error, so checking the role first would answer 403 to a caller with no key at all. Each answer needs its own return.


STEP 1 OF 8
    Ctrl + Enter to check

    Auth 401 403 in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free