how to decode signed cookie with a secret. #1063

Closed
opened 2026-03-13 08:20:56 -05:00 by GiteaMirror · 1 comment
Owner

Originally created by @kaleb110 on GitHub (Apr 16, 2025).

how to extract a cookie value in my go server?

package middleware

import (
	"context"
	"log"
	"net/http"
	"net/url"
	"os"

	"github.com/golang-jwt/jwt/v5"
)

type contextKey string

const userIDContextKey contextKey = "user_id"

func AuthMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 1. Get the cookie
		cookie, err := r.Cookie("custom_cookie") 
		if err != nil {
			log.Printf("Cookie error: %v", err)
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		// 2. URL-decode the value (since it contains %2B, %3D, etc.)
		decodedValue, err := url.QueryUnescape(cookie.Value)
		if err != nil {
			log.Printf("URL decode error: %v", err)
			http.Error(w, "Invalid cookie", http.StatusBadRequest)
			return
		}

		log.Print("log", decodedValue)
		// 3. Parse the JWT
		token, err := jwt.Parse(decodedValue, func(token *jwt.Token) (interface{}, error) {
			return []byte(os.Getenv("BETTER_AUTH_SECRET")), nil 
		})
		if err != nil {
			log.Printf("JWT parse error: %v", err)
			http.Error(w, "Invalid token", http.StatusUnauthorized)
			return
		}

		// 4. Extract claims
		claims, ok := token.Claims.(jwt.MapClaims)
		if !ok || !token.Valid {
			log.Printf("Invalid JWT claims")
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		// 5. Get user_id (adjust claim key as needed)
		userID, ok := claims["id"].(string)
		if !ok {
			log.Printf("user_id not found in claims: %+v", claims)
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		// 6. Attach to context and proceed
		ctx := context.WithValue(r.Context(), userIDContextKey, userID)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

func GetUserIDFromContext(ctx context.Context) (string, bool) {
	userID, ok := ctx.Value(userIDContextKey).(string)
	return userID, ok
}
Originally created by @kaleb110 on GitHub (Apr 16, 2025). how to extract a cookie value in my go server? ``` package middleware import ( "context" "log" "net/http" "net/url" "os" "github.com/golang-jwt/jwt/v5" ) type contextKey string const userIDContextKey contextKey = "user_id" func AuthMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // 1. Get the cookie cookie, err := r.Cookie("custom_cookie") if err != nil { log.Printf("Cookie error: %v", err) http.Error(w, "Unauthorized", http.StatusUnauthorized) return } // 2. URL-decode the value (since it contains %2B, %3D, etc.) decodedValue, err := url.QueryUnescape(cookie.Value) if err != nil { log.Printf("URL decode error: %v", err) http.Error(w, "Invalid cookie", http.StatusBadRequest) return } log.Print("log", decodedValue) // 3. Parse the JWT token, err := jwt.Parse(decodedValue, func(token *jwt.Token) (interface{}, error) { return []byte(os.Getenv("BETTER_AUTH_SECRET")), nil }) if err != nil { log.Printf("JWT parse error: %v", err) http.Error(w, "Invalid token", http.StatusUnauthorized) return } // 4. Extract claims claims, ok := token.Claims.(jwt.MapClaims) if !ok || !token.Valid { log.Printf("Invalid JWT claims") http.Error(w, "Unauthorized", http.StatusUnauthorized) return } // 5. Get user_id (adjust claim key as needed) userID, ok := claims["id"].(string) if !ok { log.Printf("user_id not found in claims: %+v", claims) http.Error(w, "Unauthorized", http.StatusUnauthorized) return } // 6. Attach to context and proceed ctx := context.WithValue(r.Context(), userIDContextKey, userID) next.ServeHTTP(w, r.WithContext(ctx)) }) } func GetUserIDFromContext(ctx context.Context) (string, bool) { userID, ok := ctx.Value(userIDContextKey).(string) return userID, ok } ```
Author
Owner

@Bekacru commented on GitHub (Apr 17, 2025):

for session token
format -> "value.signature"

step1: separate with '.' delimeter
step2: decode
step3: take the value and validate the signature using hmac with your BA Secret Key

@Bekacru commented on GitHub (Apr 17, 2025): for session token format -> "value.signature" step1: separate with '.' delimeter step2: decode step3: take the value and validate the signature using hmac with your BA Secret Key
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#1063