Go JWT Authentication for REST APIs

Updated 9 min read
Go JWT Authentication featured image: cards for issuing, sending and verifying tokens

Go JWT authentication lets your API remember who a user is without storing a session on the server. In this post, you will learn what a JSON Web Token is and how its three parts work. Also, you will see why the signature matters. Then we will build login, a token check middleware and a protected route for our book API.

This lesson continues straight from Go password hashing with bcrypt. There, users learned to log in safely. We also use middleware from Go middleware explained with examples and context values from Go context for beginners.

What Is Go JWT Authentication?

In short, a JSON Web Token, or JWT, is a small signed string. It carries facts about a user, such as their email and role. So after a correct login, the server creates a JWT and gives it to the client. Then the client sends it back with every request, usually in the Authorization header. Because the token itself holds the user details, the server does not need to look anything up.

For example, think of a wristband at a music festival. First, at the gate, staff check your ticket once and give you a band. After that, every stage only looks at the band, so nobody checks your ticket again. Similarly, the server checks the password once and then trusts the signed token.

In Go, the most popular library for this is github.com/golang-jwt/jwt/v5. So that is what we use here. It is well tested and follows the JWT standard closely, and its version 5 added clearer errors.

Why Go JWT Authentication Matters

Traditionally, classic sessions store login state in server memory or a database. However, modern backends often run many servers and services. Specifically, here is where Go JWT authentication helps.

  • Stateless servers: any server can check a token, so you do not need shared session storage.
  • Microservices: one auth service issues tokens, and every other service verifies them.
  • Mobile apps and SPAs: clients simply attach the token to each API call.
  • Built-in expiry: every token carries its own end time.
  • Roles and permissions: claims such as role travel with each request.

In short, Go JWT authentication fits APIs that serve many clients from many servers.

How Go JWT Authentication Works

First, the user sends an email and password to /login. After that, the server checks the password with bcrypt and creates a signed token. Then the client stores the token and sends Authorization: Bearer <token> on later requests. Finally, a middleware verifies the signature and expiry before the handler runs.

Go JWT Authentication diagram showing login, token issue, Bearer requests and middleware checks
The client logs in once, receives a signed token, and then sends it as a Bearer header on every request for the middleware to verify.

Above all, the key idea is the signature. In fact, the server signs the token with a secret key that only it knows. As a result, if anyone changes even one letter of the token, the signature check fails.

The Three Parts of a JWT

Overall, a JWT is three Base64URL strings joined by dots: header, payload and signature. For example, here is a real token we signed with HS256 for this post.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYWRtaW4iLCJpc3MiOiJib29rc3RvcmUiLCJzdWIiOiJhc2hhQGV4YW1wbGUuY29tIiwiZXhwIjoxNzg4OTI1NTAwLCJpYXQiOjE3ODg5MjQ2MDB9.xFDOrrhdQr7rCbFNo51pUhWSWaeyVzsQlg4E8zMXY5E

Then, decoding the first two parts gives plain JSON. So the header is {"alg":"HS256","typ":"JWT"}, and the payload is shown below.

{"role":"admin","iss":"bookstore","sub":"asha@example.com","exp":1788925500,"iat":1788924600}

However, anyone can read the payload. Therefore, never put passwords or other secrets in a JWT. In other words, the signature only proves the data was not changed; it does not hide it.

Standard Claims

Claims are the fields inside the payload. So this table lists the standard ones you will use most.

ClaimNameExample use
subSubjectThe user’s email or ID
issIssuerWhich service created the token
expExpires atReject the token after this time
iatIssued atWhen the token was created
audAudienceWhich service the token is for

Go JWT Authentication vs Server Sessions

Both approaches keep users logged in. However, they store state in different places, as the table below shows.

FeatureJWTServer session
Where state livesInside the signed tokenIn server memory or a database
Works across many serversYes, with the same keyNeeds shared session storage
Logout right awayHard, token valid until expiryEasy, delete the session
Size per requestLarger headerSmall cookie ID
Best forAPIs, mobile apps, microservicesClassic server-rendered websites
Go JWT Authentication vs sessions diagram comparing where login state lives
A JWT carries the user’s claims inside the signed token, while a session cookie only carries an ID that the server looks up.

So when should you use which? Use Go JWT authentication for APIs used by apps and other services. On the other hand, sessions are simpler for a classic website where you need instant logout.

Hands-On: Protect the Book API with JWT

Now let’s add Go JWT authentication to our API with login and a protected /me route. First, add the library with go get github.com/golang-jwt/jwt/v5.

Step 1: Claims, Signing and Parsing

We define our own claims struct, then write one function to create tokens and one to check them.

var jwtKey = []byte(os.Getenv("JWT_SECRET"))

type Claims struct {
	Role string `json:"role"`
	jwt.RegisteredClaims
}

func createToken(email, role string) (string, error) {
	now := time.Now()
	claims := Claims{
		Role: role,
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    "bookstore",
			Subject:   email,
			IssuedAt:  jwt.NewNumericDate(now),
			ExpiresAt: jwt.NewNumericDate(now.Add(15 * time.Minute)),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtKey)
}

func parseToken(tokenStr string) (*Claims, error) {
	claims := &Claims{}
	_, err := jwt.ParseWithClaims(tokenStr, claims,
		func(t *jwt.Token) (any, error) { return jwtKey, nil },
		jwt.WithValidMethods([]string{"HS256"}),
		jwt.WithIssuer("bookstore"),
	)
	if err != nil {
		return nil, err
	}
	return claims, nil
}

Here, embedding jwt.RegisteredClaims gives us sub, exp and the other standard fields for free. Also, WithValidMethods makes the parser accept only HS256. As a result, an attacker cannot switch the algorithm to trick the check. Finally, ParseWithClaims checks the signature, the expiry and the issuer in one call.

Step 2: The Login Handler

Next, the login handler reuses the bcrypt UserStore from the previous lesson.

func (a *App) handleLogin(w http.ResponseWriter, r *http.Request) {
	var in struct {
		Email    string `json:"email"`
		Password string `json:"password"`
	}
	if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
		http.Error(w, "invalid JSON", http.StatusBadRequest)
		return
	}
	if err := a.users.Login(in.Email, in.Password); err != nil {
		http.Error(w, "invalid email or password", http.StatusUnauthorized)
		return
	}
	token, err := createToken(in.Email, a.users.Role(in.Email))
	if err != nil {
		http.Error(w, "could not create token", http.StatusInternalServerError)
		return
	}
	json.NewEncoder(w).Encode(map[string]string{"token": token})
}

Step 3: The Auth Middleware

Then this middleware reads the Bearer token and checks it. If the token is valid, it stores the claims in the request context.

type ctxKey string

const claimsKey ctxKey = "claims"

func RequireAuth(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		tokenStr, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
		if !ok {
			http.Error(w, "missing token", http.StatusUnauthorized)
			return
		}
		claims, err := parseToken(tokenStr)
		if err != nil {
			http.Error(w, "invalid token", http.StatusUnauthorized)
			return
		}
		ctx := context.WithValue(r.Context(), claimsKey, claims)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

func handleMe(w http.ResponseWriter, r *http.Request) {
	claims := r.Context().Value(claimsKey).(*Claims)
	json.NewEncoder(w).Encode(map[string]string{
		"email": claims.Subject, "role": claims.Role,
	})
}

To finish the setup, register the routes with mux.HandleFunc("POST /login", app.handleLogin) and mux.Handle("GET /me", RequireAuth(http.HandlerFunc(handleMe))).

Step 4: Try It with curl

Finally, log in, call the protected route without a token and then with one.

curl -s -X POST localhost:8080/login \
  -d '{"email":"asha@example.com","password":"secret123"}'
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}

curl -s localhost:8080/me
missing token

curl -s -H "Authorization: Bearer $TOKEN" localhost:8080/me
{"email":"asha@example.com","role":"admin"}

When a token fails, the library returns a clear error. For example, an expired token gives token has invalid claims: token is expired. Meanwhile, a changed token gives token signature is invalid: signature is invalid. So you can give the client a helpful message with errors.Is.

_, err := parseToken(tokenStr)
switch {
case errors.Is(err, jwt.ErrTokenExpired):
	http.Error(w, "token expired, please log in again", http.StatusUnauthorized)
case errors.Is(err, jwt.ErrTokenSignatureInvalid):
	http.Error(w, "invalid token", http.StatusUnauthorized)
case errors.Is(err, jwt.ErrTokenMalformed):
	http.Error(w, "malformed token", http.StatusBadRequest)
}

As a result, an app can show “please log in again” for an expired token. That is much better than a confusing generic error.

Refresh Tokens in Go JWT Authentication

Short access tokens are safer. However, logging in again every 15 minutes would annoy every user. So most Go JWT authentication setups add a second, longer-lived token called a refresh token.

The flow is simple. First, login returns two tokens: a 15 minute access token and a 7 day refresh token. Then the app uses the access token for normal calls. When it expires, the app sends the refresh token to /refresh and gets a new access token. Finally, on logout, the server deletes the refresh token from its database, so it can never be used again.

Because the server stores refresh tokens, it can cancel them. Meanwhile, access tokens stay stateless and fast to check. In short, you get both speed and the ability to log users out.

Common Mistakes with Go JWT Authentication

  • Weak or hard-coded secrets: anyone who guesses the key can create admin tokens. So use a long random secret from an environment variable.
  • Not restricting algorithms: attackers may try other algorithms. Always pass WithValidMethods.
  • Very long expiry times: a stolen token then works for weeks. Keep access tokens short, such as 15 minutes.
  • Secrets in the payload: anyone can decode the claims. Store only IDs, emails and roles.
  • **Tokens in localStorage with no XSS protection**: injected scripts can steal them. Consider HttpOnly cookies for browser apps.

Best Practices for Go JWT Authentication

  • Use HTTPS everywhere, because a token sent over plain HTTP can be copied.
  • Pair short access tokens with refresh tokens, so users stay logged in safely.
  • **Check iss and aud**, since that stops tokens meant for another service.
  • Keep a deny list for urgent logouts, as JWTs otherwise stay valid until expiry.
  • Rotate signing keys from time to time, and use the kid header to pick the right one.

Practice Task

To practise Go JWT authentication, add a RequireRole("admin") middleware. It should run after RequireAuth and return 403 Forbidden when the role does not match. Then protect a DELETE /books/{id} route with it.

Hint: read the claims from the context, just like handleMe does. Then test it twice: once with an admin token and once with a normal user token.

Official Resources

These pages cover the library and the JWT standard itself, so keep them handy.

Quick Recap

  • Go JWT authentication gives clients a signed token after one login.
  • A JWT has a header, a payload and a signature, joined by dots.
  • Anyone can read the payload, so never store secrets in it.
  • jwt.NewWithClaims signs tokens, and ParseWithClaims checks them.
  • A middleware reads the Bearer token and puts the claims in the context.
  • Keep tokens short-lived, restrict algorithms and always use HTTPS.

What’s Next?

At this point, our API knows who each user is. Next, we will make sure the data users send is valid before it reaches the database, with input validation.

Coming soon: Go Input Validation