Home  >  Article  >  Backend Development  >  Securing Your Go API with JWT Authentication

Securing Your Go API with JWT Authentication

Susan Sarandon
Susan SarandonOriginal
2024-10-03 12:07:01728browse

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:

  1. Add the JWT package and mux router:
   go get github.com/golang-jwt/jwt/v4
   go get github.com/gorilla/mux
  1. 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

  1. Login to generate a token:
   curl -X POST http://localhost:8000/login -d '{"username":"admin", "password":"password"}' -H "Content-Type: application/json"
  1. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn