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.
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?
Now, let’s get started with our fancy new JWT library!
For those new to JWT:
Now that you’re up to speed, let’s dive into the code!
We’re continuing from where we left off in last post. Let’s update our Go module and install the necessary packages:
go get github.com/golang-jwt/jwt/v4 go get github.com/gorilla/mux
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.
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), }) }
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.
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)) }
curl -X POST http://localhost:8000/login -d '{"username":"admin", "password":"password"}' -H "Content-Type: application/json"
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."
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!