Auth middleware
- Go course
- Advanced
- Lesson 35/68
- 4 min
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.
Practice 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.
Starter code
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func main() {
// buraya yaz
}Sample 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)
}Expected output
401
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the right status code when authentication fails?
- 404 Not Found
- 500 Internal Server Error
- 302 Found
- 401 Unauthorized Correct answer
Explanation: 401 says credentials are missing or invalid; if identity is fine but permission is missing, 403 Forbidden is used.
2 Stop the request
if token == "" {
http.Error(w, "yetkisiz", http.StatusUnauthorized)
____
}
if token == "" {
http.Error(w, "yetkisiz", http.StatusUnauthorized)
return
}
Explanation: return leaves the middleware before reaching next.ServeHTTP; the request never gets to the handler.
3 Status codes
| Term | Meaning |
|---|---|
401 |
No/invalid credentials |
403 |
No permission |
200 |
Success |
429 |
Too many requests |