Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Go Programming Bootcamp

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)))

Info

Never store raw passwords – use golang.org/x/crypto/bcrypt to hash them.

Previous: Encoding & Decoding – JSON, XML, and GobNext: WebSockets with `gorilla/websocket`