Design authentication and authorization
Design authentication and authorization
Authentication establishes who is making a request; authorization decides what that identity can do. Treat the principal as a server-created result of a verified session or token, never as a role or identity asserted by the client. This offline policy grants document access only to its authenticated owner within the same tenant.
package main
import ( "fmt")
type Principal struct { ID, Tenant string Authenticated bool}type Document struct{ Owner, Tenant string }
func allowed(p Principal, d Document) bool { return p.Authenticated && p.ID != "" && p.Tenant != "" && p.Tenant == d.Tenant && p.ID == d.Owner}func main() { d := Document{"a", "team1"} fmt.Println(allowed(Principal{"a", "team1", true}, d), allowed(Principal{"a", "team2", true}, d))}Check authorization at each relevant operation, including object and tenant boundaries. Deny by default. A hidden button or unpredictable identifier cannot enforce access control. In a real service enforce the same scope in storage queries and transactions; test reads, writes and lists independently.
Expected output:
true falseClassify access decisions
package main
import ( "fmt")
type Principal struct { ID, Tenant string Authenticated bool}type Document struct{ Owner, Tenant string }
func allowed(p Principal, d Document) bool { return p.Authenticated && p.ID != "" && p.Tenant != "" && p.Tenant == d.Tenant && p.ID == d.Owner}func decision(p Principal, d Document) int { if !p.Authenticated { return 401 } if !allowed(p, d) { return 403 } return 200}func main() { d := Document{"a", "team1"} fmt.Println(decision(Principal{}, d), decision(Principal{"b", "team1", true}, d), decision(Principal{"a", "team1", true}, d))}401 means valid authentication credentials are missing or unacceptable; a real HTTP 401 response requires an applicable WWW-Authenticate challenge. 403 means the request is understood but refused. Some services return 404 to avoid exposing object existence. Use reviewed identity libraries, check token issuer, audience and expiry, and protect session cookies and state-changing requests. This example does not validate tokens or implement login.
Expected output:
401 403 200Try it locally
Check that an empty principal and a same-tenant non-owner are both denied.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Security engineering 05: Design authentication and authorization
Check the lesson objective before moving on.
Where should ownership be checked?
What is this example testing?