Authentication and Authorization
Start with Authentication and Authorization
Learn authentication and authorization through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of authentication and authorization.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Authentication establishes who a requester is; authorization decides what that identity may do. HTTP handlers must check both where needed, and authorization must apply to each relevant resource.
A fixed bearer token is used only to illustrate the branches. Production systems need securely generated credentials, TLS, expiration or revocation policies and carefully designed identity checks.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
For deployed applications, use TLS, robust session or token handling, rate limits, audit trails and resource-level permission checks. Treat the hard-coded token here as teaching-only.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func handler(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer demo-token" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
fmt.Fprint(w, "allowed")
}
func main() {
for _, token := range []string{"", "Bearer demo-token"} {
req := httptest.NewRequest(http.MethodGet, "/admin", nil)
if token != "" {
req.Header.Set("Authorization", token)
}
rec := httptest.NewRecorder()
handler(rec, req)
fmt.Println("Status:", rec.Code)
}
}
Output
Status: 401
Status: 200Trace what the program does
The missing header produces 401; the matching demonstration token produces 200. An actual application must validate credential authenticity and check whether the verified identity has permission for this resource.
Avoid common mistakes
- Never put demo tokens or real credentials into production source code.
- An authenticated user is not automatically authorized for every resource.
Try it yourself
Add a role check for an admin-only route after validating the identity.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Authentication and Authorization in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.