### Initialize JWT Authentication and Generate Sample Token Source: https://github.com/go-chi/jwtauth/blob/master/README.md Initializes a new JWTAuth instance with a specific algorithm, secret, and nil options. It then generates and prints a sample JWT token with custom claims for debugging or demonstration purposes. ```go package main import ( "fmt" "net/http" "github.com/go-chi/chi/v5" "github.com/go-chi/jwtauth/v5" ) var tokenAuth *jwtauth.JWTAuth func init() { tokenAuth = jwtauth.New("HS256", []byte("secret"), nil) // For debugging/example purposes, we generate and print // a sample jwt token with claims `user_id:123` here: _, tokenString, _ := tokenAuth.Encode(map[string]interface{}{"user_id": 123}) fmt.Printf("DEBUG: a sample jwt is %s\n\n", tokenString) } func main() { addr := ":3333" fmt.Printf("Starting server on %v\n", addr) http.ListenAndServe(addr, router()) } func router() http.Handler { r := chi.NewRouter() // Protected routes r.Group(func(r chi.Router) { // Seek, verify and validate JWT tokens r.Use(jwtauth.Verifier(tokenAuth)) // Handle valid / invalid tokens. In this example, we use // the provided authenticator middleware, but you can write your // own very easily, look at the Authenticator method in jwtauth.go // and tweak it, its not scary. r.Use(jwtauth.Authenticator(tokenAuth)) r.Get("/admin", func(w http.ResponseWriter, r *http.Request) { _, claims, _ := jwtauth.FromContext(r.Context()) w.Write([]byte(fmt.Sprintf("protected area. hi %v", claims["user_id"]))) }) }) // Public routes r.Group(func(r chi.Router) { r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("welcome anonymous")) }) }) return r } ``` -------------------------------- ### Generate JWT Token using jwtutil CLI Source: https://github.com/go-chi/jwtauth/blob/master/README.md Demonstrates how to generate a JWT token using the `jwtutil` command-line tool. This is useful for creating tokens with specific secrets and claims for testing or utility purposes. ```bash go install github.com/goware/jwtutil Usage: jwtutil -secret=secret -encode -claims='{"user_id":111}' Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMTF9._cLJn0xFS0Mdr_4L_8XF8-8tv7bHyOQJXyWaNsSqlEs ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.