Go
Auth middleware
Learn to write an auth middleware that validates tokens.
Auth middleware
Authentication middleware checks credentials before passing the request to the handler. If they are invalid it returns 401 Unauthorized and doesn't call next:
func yetki(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer gizli" {
http.Error(w, "yetkisiz", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
Carrying the user through context
The authenticated user is passed to the handler through context:
type ctxKey struct{}
ctx := context.WithValue(r.Context(), ctxKey{}, "ada")
next.ServeHTTP(w, r.WithContext(ctx))
// in the handler
kullanici := r.Context().Value(ctxKey{}).(string)
Using an unexported type as the key avoids collisions with other packages.
Exercise Token check
Write yetki(next http.Handler) http.Handler: if the X-Token header isn't "abc", return with http.Error(w, "yetkisiz", http.StatusUnauthorized). Send a request without the header and print rec.Code.
Show example solution
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func yetki(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Token") != "abc" {
http.Error(w, "yetkisiz", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
h := yetki(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
fmt.Println(rec.Code)
}
Test yourself
-
What is the right status code when authentication fails?
- 404 Not Found
- 500 Internal Server Error
- 302 Found
- 401 Unauthorized
Show answer
401 Unauthorized — 401 says credentials are missing or invalid; if identity is fine but permission is missing, 403 Forbidden is used.
-
Stop the request
if token == "" {
http.Error(w, "yetkisiz", http.StatusUnauthorized)
____
}
Show answer
if token == "" {
http.Error(w, "yetkisiz", http.StatusUnauthorized)
return
}
-
Status codes
- 401
- No/invalid credentials
- 403
- No permission
- 200
- Success
- 429
- Too many requests
Next lesson: Summary - Middleware