DEV Community

Juma
Juma

Posted on

Authentication with JWT

Tokens, Refresh Flows, and Common Mistakes

Picture a theme park. At the gate, a staff member checks your ticket once, carefully, then fastens a colored wristband to your arm. For the rest of the day, no one asks to see your ticket again. They glance at the wristband and wave you onto the roller coaster.

That's the idea behind token-based authentication. You prove who you are once, with a password. The server hands back a token, your wristband, and from then on you present the token with each request. A JWT (JSON Web Token, usually pronounced "jot") is a popular kind of wristband.

JWTs are also one of the most commonly misused tools in backend development. Used well, they're simple and scalable. Used carelessly, they're the theme park equivalent of wristbands that never expire, can be forged with a marker pen, and have your home address printed on them. This article shows you how to do it properly in Go.

What a JWT actually is

A JWT is a string made of three parts separated by dots:

xxxxx.yyyyy.zzzzz
Enter fullscreen mode Exit fullscreen mode
  1. Header: says which algorithm was used to sign the token.
  2. Payload: the claims, which are facts about the user and the token (who they are, when it expires).
  3. Signature: a cryptographic seal over the first two parts.

Each part is Base64URL-encoded JSON, except the signature. Decode the payload and you'll see something like:

{
  "sub": "42",
  "role": "member",
  "iat": 1760000000,
  "exp": 1760000900
}
Enter fullscreen mode Exit fullscreen mode

Here sub is the subject (the user ID), iat is "issued at," and exp is the expiry time. These are standard registered claims, and you can add your own, like role.

The most important thing to understand

A JWT is signed, not encrypted. Anyone holding the token can read the payload. Just paste one into a decoder and it's right there. The signature doesn't hide the contents. It only proves nobody changed them.

This leads to rule one: never put secrets in a JWT. No passwords, no full addresses, no national ID numbers. A user ID and a role are plenty.

Why the signature matters

Suppose a mischievous user decodes their token, changes "role": "member" to "role": "admin", and sends it back. Your server recomputes the signature using its secret key. The numbers don't match. Token rejected. The signature is a wax seal on a letter: the contents are readable, but you can't alter them without breaking it.

Only someone with the signing key can produce a valid seal. Protect that key like the master key to the whole park.

Signing choices: HS256 vs RS256 (briefly)

Two common options:

  • HS256 (HMAC with a shared secret): one secret both signs and verifies. Simple. Great when a single service issues and checks tokens.
  • RS256 / EdDSA (public-private key pair): a private key signs, a public key verifies. Better when many services need to verify tokens without being able to create them.

For a typical single backend, HS256 with a long, random secret is perfectly good. If you later split into multiple services, consider asymmetric keys.

Creating tokens in Go

We'll use the widely adopted github.com/golang-jwt/jwt/v5 package.

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

type TokenService struct {
    secret     []byte
    accessTTL  time.Duration
    issuer     string
}

func (t *TokenService) NewAccessToken(userID uint, role string) (string, error) {
    now := time.Now()
    claims := Claims{
        Role: role,
        RegisteredClaims: jwt.RegisteredClaims{
            Subject:   strconv.FormatUint(uint64(userID), 10),
            Issuer:    t.issuer,
            IssuedAt:  jwt.NewNumericDate(now),
            ExpiresAt: jwt.NewNumericDate(now.Add(t.accessTTL)),
        },
    }

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    signed, err := token.SignedString(t.secret)
    if err != nil {
        return "", fmt.Errorf("signing token: %w", err)
    }
    return signed, nil
}
Enter fullscreen mode Exit fullscreen mode

Notice the expiry. Every token needs one. A token that never expires is a wristband that works until the heat death of the universe, and if it ever leaks, you can't take it back.

Verifying tokens (where most security bugs hide)

Verification is the dangerous half. Here's a careful version:

func (t *TokenService) Verify(raw string) (*Claims, error) {
    claims := &Claims{}

    token, err := jwt.ParseWithClaims(raw, claims,
        func(tok *jwt.Token) (interface{}, error) {
            return t.secret, nil
        },
        jwt.WithValidMethods([]string{"HS256"}),
        jwt.WithIssuer(t.issuer),
        jwt.WithExpirationRequired(),
    )
    if err != nil {
        return nil, fmt.Errorf("verifying token: %w", err)
    }
    if !token.Valid {
        return nil, errors.New("invalid token")
    }
    return claims, nil
}
Enter fullscreen mode Exit fullscreen mode

Look at the options, because each one closes a known hole.

WithValidMethods pins the allowed algorithm. This matters because of a famous class of attacks: the token's header declares which algorithm to use, and a naive server that obeys the header can be tricked. The "none" algorithm attack sends a token claiming it needs no signature at all. A careless library might accept it. Another trick, "algorithm confusion," convinces a server to treat a public key as an HMAC secret. Decide on the algorithm yourself, on the server, and refuse anything else. The token doesn't get a vote.

WithIssuer rejects tokens minted by someone else.

WithExpirationRequired refuses tokens without an exp. Combined with the library's standard expiry check, stale tokens are rejected.

Wiring it into Gin

Remember the auth bouncer from the middleware article? Here it is with real verification:

func RequireAuth(tokens *auth.TokenService) 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 token"})
            return
        }

        claims, err := tokens.Verify(raw)
        if err != nil {
            c.AbortWithStatusJSON(http.StatusUnauthorized,
                gin.H{"error": "invalid or expired token"})
            return
        }

        uid, err := strconv.ParseUint(claims.Subject, 10, 64)
        if err != nil {
            c.AbortWithStatusJSON(http.StatusUnauthorized,
                gin.H{"error": "invalid token"})
            return
        }

        c.Set("userID", uint(uid))
        c.Set("role", claims.Role)
        c.Next()
    }
}
Enter fullscreen mode Exit fullscreen mode

The client sends the token in a header: Authorization: Bearer <token>. The middleware validates it, stores the user ID and role in the context, and the handler carries on.

Note that the error messages stay vague: "invalid or expired token" doesn't tell an attacker which thing went wrong. Specifics go to your logs, not your responses.

The expiry dilemma: short-lived vs long-lived

Here's the tension. A short expiry, say 15 minutes, limits the damage if a token is stolen. But making users log in every 15 minutes is a recipe for abandoned apps. A long expiry, say 30 days, is convenient but turns a stolen token into a month-long free pass.

JWTs have an uncomfortable property: they're stateless. The server doesn't remember issuing them, so it can't easily "cancel" one. Once signed, a token is good until it expires. That's the very feature that makes them scalable and the very reason they're hard to revoke.

The standard solution is a two-token system.

Access tokens and refresh tokens

  • Access token: short-lived (about 10 to 15 minutes), a JWT, sent with every API request.
  • Refresh token: long-lived (days or weeks), used only to get a new access token.

The flow:

  1. User logs in with email and password.
  2. Server returns an access token and a refresh token.
  3. Client uses the access token for API calls.
  4. When it expires (the API returns 401), the client sends the refresh token to /auth/refresh.
  5. Server checks the refresh token and issues a fresh access token, and ideally a new refresh token too.

Back to the theme park: the access token is a wristband that changes color every 15 minutes. The refresh token is a membership card you show at the kiosk to get a new wristband. The wristband is used constantly and could be dropped on a ride. The membership card stays in your pocket and only comes out occasionally.

Make refresh tokens revocable

Here's the key insight: because the refresh token is used rarely and checked against your database, you can make it stateful. Store a hash of each refresh token in a table:

CREATE TABLE refresh_tokens (
    id         BIGSERIAL PRIMARY KEY,
    user_id    BIGINT      NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    token_hash TEXT        NOT NULL UNIQUE,
    expires_at TIMESTAMPTZ NOT NULL,
    revoked_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
Enter fullscreen mode Exit fullscreen mode

Generate the refresh token as a long random string (not necessarily a JWT), and store only its hash, just as you would a password. If your database leaks, the attacker gets hashes they can't use.

func NewRefreshToken() (raw string, hash string, err error) {
    b := make([]byte, 32)
    if _, err = rand.Read(b); err != nil { // crypto/rand
        return "", "", err
    }
    raw = base64.RawURLEncoding.EncodeToString(b)
    sum := sha256.Sum256([]byte(raw))
    hash = hex.EncodeToString(sum[:])
    return raw, hash, nil
}
Enter fullscreen mode Exit fullscreen mode

(SHA-256 is fine here, unlike for passwords, because the token is already long and random. There's nothing to brute-force.)

Now "log out" means marking the row revoked. "Log out everywhere" means revoking all rows for that user. You've regained control.

Rotate on use

Even better: refresh token rotation. Every time a refresh token is used, mark it as used and issue a new one. If an old, already-used refresh token ever shows up again, someone is replaying a stolen token, so revoke the whole family and force a fresh login. It's the park noticing two people showing the same membership card in different corners at the same time.

Where should the client keep the token?

This is a lively debate, so here's the honest trade-off for your vanilla JavaScript frontend.

localStorage: easy, but any JavaScript on your page can read it. If an attacker injects a script (XSS), they can steal the token.

HttpOnly cookie: JavaScript can't read it at all, which defeats most token theft via XSS. But cookies are sent automatically, which opens the door to CSRF attacks unless you add protections like SameSite=Lax or Strict and anti-CSRF measures.

A reasonable pattern for web apps: keep the refresh token in an HttpOnly, Secure, SameSite cookie, and keep the short-lived access token in memory (a JavaScript variable). If the page reloads, silently call the refresh endpoint to get a new access token. It's a bit more setup, but the dangerous long-lived credential never touches JavaScript-readable storage.

Whatever you choose, always serve over HTTPS. A token sent over plain HTTP is a postcard.

Common mistakes

Putting sensitive data in the payload. It's readable by anyone. Treat it like a postcard.

Skipping expiry. Immortal tokens are a liability. Always set exp.

Hard-coding or weakly choosing the secret. secret123 can be brute-forced. Use at least 32 random bytes, loaded from the environment, never committed to git.

Trusting the header's algorithm. Pin your allowed methods in code.

Using the access token for too long "to avoid refresh logic." That's trading security for laziness. Build the refresh flow once, and it works forever.

Not checking the token's claims against reality. If a user is deleted or banned, a still-valid access token keeps working until it expires. For sensitive actions, you may want a quick database check, one more reason to keep access tokens short.

Treating JWT as a session replacement for everything. If you need instant revocation on every request, classic server-side sessions might fit better. JWTs aren't a moral achievement, just a tool with specific trade-offs.

Storing refresh tokens in plaintext. Hash them. Always.

Quick recap

  • A JWT is a signed, readable package of claims. It's signed, not encrypted, so keep secrets out.
  • Always set expiry, issuer, and pin the allowed signing algorithm when verifying.
  • Use short-lived access tokens plus longer-lived, revocable refresh tokens stored as hashes.
  • Rotate refresh tokens and treat reuse as a theft alarm.
  • Keep long-lived credentials out of JavaScript-readable storage where possible, and always use HTTPS.
  • Load the signing secret from the environment, and make it long and random.

Top comments (0)