CodeBlanks Logo Icon CodeBlanks

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.

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

main.go
package main

import (
    "fmt"
    "net/http"
    "net/http/httptest"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
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

Question
if token == "" {
    http.Error(w, "yetkisiz", http.StatusUnauthorized)
    ____
}
Answer
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

All lessons in Advanced