Lesson 37 of 60 · Go
Authentication – JWT and Middleware
Duration: 25 minutes
JSON Web Tokens (JWT)
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
import (
"github.com/golang-jwt/jwt/v5"
"time"
)
func GenerateToken(userID string) (string, error) {
claims := jwt.MapClaims{"sub": userID, "exp": time.Now().Add(time.Hour).Unix()}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte("my-secret-key"))
}
Middleware for validation
func JWTAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if auth == "" { http.Error(w, "missing token", http.StatusUnauthorized); return }
tokenStr := strings.TrimPrefix(auth, "Bearer ")
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
return []byte("my-secret-key"), nil
})
if err != nil || !token.Valid { http.Error(w, "invalid token", http.StatusUnauthorized); return }
next.ServeHTTP(w, r)
})
}
Register it:
mux := http.NewServeMux()
mux.Handle("/protected", JWTAuth(http.HandlerFunc(protected)))