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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Authentication – JWT and Mi | Go Programming Bootcamp lesson | BraveProgrammer
  1. Courses
  2. /
  3. Go Programming Bootcamp

Lesson 37 of 60

·Go

Authentication – JWT and Middleware

25 minutes

Course progress62%

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) (, ) {
    claims := jwt.MapClaims{: userID, : time.Now().Add(time.Hour).Unix()}
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
     token.SignedString([]())
}
string
error
"sub"
"exp"
return
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.
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from Go Programming BootcampBrowse activities
Previous lessonEncoding & Decoding – JSON, XML, and GobContinue to lesson 38WebSockets with `gorilla/websocket`Back to Go Programming Bootcamp curriculum