BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: JWT Authentication

Go 1.23

Secure your applications with JSON Web Tokens (JWT). This example demonstrates how to generate signed tokens with custom claims and validate incoming tokens using the `golang-jwt` package, a standard for stateless authentication.

Code

package main

import (
    "fmt"
    "time"
    "github.com/golang-jwt/jwt/v5"
)

var hmacSampleSecret = []byte("my_secret_key")

func main() {
    // 1. Create a new token with claims
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
        "foo": "bar",
        "nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
    })

    // 2. Sign the token with our secret
    tokenString, err := token.SignedString(hmacSampleSecret)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Token:", tokenString)
    
    // 3. Parse and validate the token
    parsedToken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
        // Validate the signing algorithm
        if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
            return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
        }
        return hmacSampleSecret, nil
    })

    // 4. Check validity and access claims
    if claims, ok := parsedToken.Claims.(jwt.MapClaims); ok && parsedToken.Valid {
        fmt.Println("foo:", claims["foo"])
        fmt.Println("nbf:", claims["nbf"])
    } else {
        fmt.Println(err)
    }
}

Explanation

JSON Web Tokens (JWT) are the industry standard for stateless authentication. A JWT is a compact, URL-safe string that represents claims to be transferred between two parties. In Go, the golang-jwt/jwt/v5 package is the recommended library for handling JWTs.

Security Best Practices:

  • Algorithm Verification: Always verify that the token's signing algorithm matches your expectation (e.g., HMAC SHA256) to prevent "none" algorithm attacks.
  • Secure Storage: Never store JWTs in LocalStorage due to XSS risks. Use HttpOnly, Secure Cookies for browser clients.
  • Short Expiration: Keep access token lifespans short (e.g., 15 minutes) and implement a Refresh Token rotation strategy for long-term sessions.

Code Breakdown

13
jwt.NewWithClaims creates a new token object. We specify the signing method (HS256) and the claims (payload). jwt.MapClaims is a convenient map[string]interface{}.
19
token.SignedString generates the actual JWT string. It signs the header and payload with our secret key (hmacSampleSecret). This string is what you send to the client.
27
jwt.Parse parses the token string. The callback function is critical: it must return the secret key used to verify the signature.
29
Inside the callback, we explicitly check token.Method. This prevents attackers from bypassing verification by changing the header's "alg" to "none" or an asymmetric algorithm we don't use.
36
We type-assert the claims to jwt.MapClaims and check parsedToken.Valid. If both are true, the token is authentic and untampered, and we can safely use the data.