Apply authentication authorization and rate limits
Apply authentication authorization and rate limits
Authentication establishes who is making a request. Authorization decides whether that identity can perform the specific action on the specific resource. Rate limiting bounds accepted work. These are separate controls. Use a reviewed identity provider or authentication library; validate credentials before deriving the identity. Never trust a client-supplied owner or role field.
package main
import ( "fmt")
type Identity struct { ID string Verified bool}
func canRead(who Identity, owner string) int { if !who.Verified || who.ID == "" { return 401 } if who.ID != owner { return 403 } return 200}func main() { for _, who := range []Identity{{"", false}, {"u2", true}, {"u1", true}} { fmt.Println(canRead(who, "u1")) }}The Verified flag is set by a fictional trusted authentication boundary, not by JSON or a request header. This is an offline policy check; no real authentication happens. Missing or invalid credentials normally yield 401 with an applicable WWW-Authenticate challenge in an actual HTTP response. Authenticated but unauthorized callers receive 403 or, under a deliberate existence-hiding policy, 404.
Expected output:
401403200Bound accepted work per identity
package main
import ( "fmt" "sync")
type Quota struct { mu sync.Mutex used map[string]int limit int}
func (q *Quota) allow(id string) bool { q.mu.Lock() defer q.mu.Unlock() if q.used == nil { q.used = map[string]int{} } if q.used[id] >= q.limit { return false } q.used[id]++ return true}func main() { q := Quota{limit: 2} for _, id := range []string{"u1", "u1", "u1", "u2"} { if q.allow(id) { fmt.Println(200) } else { fmt.Println(429) } }}This toy counter represents one fixed interval whose reset is not implemented. It is not a production rate limiter. An actual limiter needs time-based refill or reset, bounded identity storage, synchronized or distributed accounting, and a documented Retry-After policy where appropriate. Apply admission limits before expensive work; use trusted identity, not arbitrary headers. A rate limit does not replace authorization.
Expected output:
200200429200Try it locally
Combine canRead and Quota in a policy simulation: only authorized requests consume quota, limit 1 for u1. Check unverified u1, verified u2, then verified u1 twice. Print the four status codes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
REST API 06: Apply authentication authorization and rate limits
Check the lesson objective before moving on.
Which check prevents reading another user’s record?
What is missing from this toy quota?