Securing Your Go API with JWT Authentication
Alright, let’s get real for a second. Security is a big deal, and if you’re building APIs, you can’t just let anyone waltz in and start messing with your data. That’s where JWT (JSON Web Tokens) comes in to save the day. Today, we’re leveling up our Go API by adding JWT-based authentication.
A Quick Heads-Up ?
If you’ve been using the old github.com/dgrijalva/jwt-go package, it’s time for an upgrade. The new standard is github.com/golang-jwt/jwt/v4.
Why the switch?
- The original author handed over the reins, and the new maintainers have been busy making improvements and fixing security issues.
- Starting from version 4.0.0, they added Go module support and improved token validation.
- Check out their MIGRATION_GUIDE.md if you're still using the old package.
Now, let’s get started with our fancy new JWT library!
What’s JWT Again? ?
For those new to JWT:
- It’s like a signed permission slip for accessing your API.
- The API generates a token, signs it, and the client (user, app, etc.) includes that token in every request.
- The server checks the token and says, "Yup, you’re legit."
Now that you’re up to speed, let’s dive into the code!
Setting Up the Project
We’re continuing from where we left off in last post. Let’s update our Go module and install the necessary packages:
- Add the JWT package and mux router:
go get github.com/golang-jwt/jwt/v4 go get github.com/gorilla/mux
- Open your main.go file, and let’s get coding!
Step 1: Generate a JWT Token
First, we’ll create a function that generates a JWT token when a user logs in. This token will contain the username and will be signed using a secret key.
var jwtKey = []byte("my_secret_key") type Credentials struct { Username string `json:"username"` Password string `json:"password"` } type Claims struct { Username string `json:"username"` jwt.RegisteredClaims } func generateToken(username string) (string, error) { expirationTime := time.Now().Add(5 * time.Minute) claims := &Claims{ Username: username, RegisteredClaims: jwt.RegisteredClaims{ ExpiresAt: jwt.NewNumericDate(expirationTime), }, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) tokenString, err := token.SignedString(jwtKey) return tokenString, err }
This function generates a token that expires after 5 minutes, signed using the HS256 algorithm.
Step 2: Create the Login Endpoint
Next, we’ll build a login endpoint where users send their credentials. If the login info checks out, we’ll generate a JWT and send it back in a cookie.
func login(w http.ResponseWriter, r *http.Request) { var creds Credentials err := json.NewDecoder(r.Body).Decode(&creds) if err != nil { w.WriteHeader(http.StatusBadRequest) return } if creds.Username != "admin" || creds.Password != "password" { w.WriteHeader(http.StatusUnauthorized) return } token, err := generateToken(creds.Username) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } http.SetCookie(w, &http.Cookie{ Name: "token", Value: token, Expires: time.Now().Add(5 * time.Minute), }) }
Step 3: Middleware for JWT Validation
Now, we need a middleware function to validate JWT tokens before allowing access to protected routes.
func authenticate(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := r.Cookie("token") if err != nil { if err == http.ErrNoCookie { w.WriteHeader(http.StatusUnauthorized) return } w.WriteHeader(http.StatusBadRequest) return } tokenStr := c.Value claims := &Claims{} tkn, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) { return jwtKey, nil }) if err != nil || !tkn.Valid { w.WriteHeader(http.StatusUnauthorized) return } next.ServeHTTP(w, r) }) }
This middleware checks if the request has a valid JWT token. If not, it returns an unauthorized response.
Step 4: Protecting Routes
Now, let’s apply our authenticate middleware to protect the /books route:
func main() { r := mux.NewRouter() r.HandleFunc("/login", login).Methods("POST") r.Handle("/books", authenticate(http.HandlerFunc(getBooks))).Methods("GET") fmt.Println("Server started on port :8000") log.Fatal(http.ListenAndServe(":8000", r)) }
Testing the API
- Login to generate a token:
curl -X POST http://localhost:8000/login -d '{"username":"admin", "password":"password"}' -H "Content-Type: application/json"
- Access the protected /books endpoint:
curl --cookie "token=<your_token>" http://localhost:8000/books
If the token is valid, you’ll get access. If not, you’ll get a "401 Unauthorized."
What’s Next?
Next time, we’ll connect our API to a database to manage user credentials and store data. Stay tuned for more!
The above is the detailed content of Securing Your Go API with JWT Authentication. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.
