Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 39 ยท Authentication and Security

JWT Authentication in Gin

Protect a Gin API with JSON Web Tokens: how a JWT is built and verified, issuing access and refresh tokens, a Bearer auth middleware, roles, and the mistakes that break security.

Cookie sessions suit browsers that talk to one server. APIs consumed by mobile apps, single-page apps and other services often prefer tokens: the client sends Authorization: Bearer <token> with every request, and the server decides from the token alone who is calling. The most common token format is the JSON Web Token (JWT). This lesson explains what is inside one, how to verify it correctly in a Gin middleware, and where JWTs go wrong. For the general Go view, see also JWT in Go.

The real code uses github.com/golang-jwt/jwt/v5, which is not available in the in-page runner, so it is shown read-only. To understand exactly what the library does, the runnable examples implement HS256 tokens by hand with crypto/hmac. Do not use hand-written token code in production; use it here to learn.

Anatomy of a JWT

A JWT is three base64url strings joined by dots: header.payload.signature.

  • Header: {"alg":"HS256","typ":"JWT"}, the signing algorithm.
  • Payload (the claims): {"sub":"42","role":"admin","exp":1767225600}. Standard claims include sub (subject, the user), exp (expiry), iat (issued at), nbf (not before), iss (issuer) and aud (audience).
  • Signature: an HMAC (or RSA/ECDSA signature) over header.payload using a secret key.

The payload is encoded, not encrypted: anyone holding the token can read it. The signature only guarantees it has not been modified. So never put secrets or private data in claims.

Create and verify a token

Go Build and verify an HS256 token by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The tampered token fails, because the signature no longer matches the changed payload. That is the whole security model: nobody without the secret can create a valid signature.

The real library

Go
import "github.com/golang-jwt/jwt/v5"

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

func issueToken(userID uint, role string) (string, error) {
	claims := Claims{
		Role: role,
		RegisteredClaims: jwt.RegisteredClaims{
			Subject:   strconv.Itoa(int(userID)),
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(15 * time.Minute)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			Issuer:    "shop-api",
		},
	}
	return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(jwtSecret)
}

func parseToken(raw string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(raw, &Claims{}, func(t *jwt.Token) (any, error) {
		return jwtSecret, nil
	}, jwt.WithValidMethods([]string{"HS256"}), jwt.WithIssuer("shop-api"))
	if err != nil {
		return nil, err
	}
	return token.Claims.(*Claims), nil
}

jwt.WithValidMethods is not optional decoration: it blocks the infamous algorithm confusion attacks (a token claiming alg: none, or switching RS256 to HS256). Always pin the algorithm you issue. Expiry (exp) is checked for you.

The Gin middleware

Go
func AuthRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		header := c.GetHeader("Authorization")
		raw, found := strings.CutPrefix(header, "Bearer ")
		if !found || raw == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing bearer token"})
			return
		}
		claims, err := parseToken(raw)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid or expired token"})
			return
		}
		c.Set("userID", claims.Subject)
		c.Set("role", claims.Role)
		c.Next()
	}
}

func RequireRole(role string) gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.GetString("role") != role {
			c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "forbidden"})
			return
		}
		c.Next()
	}
}

api := r.Group("/api", AuthRequired())
api.GET("/me", me)
api.DELETE("/users/:id", RequireRole("admin"), deleteUser)

Two details: AbortWithStatusJSON stops the chain (a plain c.JSON followed by return would let later handlers run if other middleware calls c.Next), and 401 versus 403 matter. 401 means "I do not know who you are" and 403 means "I know you, and you may not". Write the same logic for any stack as the next example does with net/http.

Go Bearer middleware with 401 and 403

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Access and refresh tokens

A JWT cannot be revoked by itself: until exp, anyone who holds it is accepted. So keep access tokens short-lived (5 to 15 minutes) and pair them with a refresh token:

  1. Login returns an access token (JWT, 15 min) and a refresh token (random string, 7 to 30 days).
  2. The server stores only a hash of the refresh token, with the user and expiry.
  3. When the access token expires, the client calls POST /auth/refresh with the refresh token and gets a new pair.
  4. Rotate: each refresh token works once; the old one is deleted. If a used token appears again, someone stole it, so revoke the whole family.
  5. Logout deletes the refresh token on the server.

Where to keep the token on the client

Local storage is readable by any script on the page (XSS steals it). An HttpOnly SameSite cookie is safer for browser apps but needs CSRF thought (next lesson). Mobile apps use the system keychain. Never put a JWT in a URL, since URLs end up in logs and referrer headers.

Common mistakes

  • Not pinning the algorithm, or accepting alg: none.
  • A weak or hard-coded secret; use 32 or more random bytes from the environment, and rotate it.
  • Long-lived access tokens with no refresh and no way to revoke.
  • Trusting claims such as role for rights that must be checked against fresh data.
  • Storing sensitive data in the payload, which is only base64.
  • Returning 200 with an error message instead of 401 or 403.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the signature of a JWT protect?

    A JWT payload is only base64-encoded; the signature provides integrity, not secrecy.
  2. 2. Which status code means 'authenticated, but not allowed'?

    401 is for missing or invalid credentials, 403 for a known user without permission.
  3. 3. Why use jwt.WithValidMethods([]string{"HS256"})?

    Pinning the algorithm prevents algorithm-confusion attacks.
  4. 4. Why pair short-lived access tokens with refresh tokens?

    Short access tokens expire quickly, and refresh tokens are stored server-side where they can be revoked and rotated.
  5. 5. What does c.AbortWithStatusJSON do compared with c.JSON?

    Abort prevents the pending handlers from running, which is what an auth failure needs.

Summary

  • A JWT is header.payload.signature; the payload is readable, the signature prevents tampering.
  • Verify the signature first, pin the algorithm, check exp and the issuer.
  • A middleware extracts the Bearer token, aborts with 401 on failure and stores claims with c.Set.
  • Use 403 for missing permission; keep access tokens short and rotate refresh tokens stored server-side as hashes.

Next: CORS, CSRF and Security Headers