The SDK provides middleware to handle bearer token authentication in Go HTTP servers. The middleware parses the token, verifies it, and extracts SessionClaims, which are then injected into the http.Request.Context().
Available Middleware
WithHeaderAuthorization(): Extracts claims and makes them available in the context. If authentication fails, it does not block the request (it's up to your handler to check).RequireHeaderAuthorization(): Similar to WithHeaderAuthorization, but automatically responds with HTTP 403 Forbidden if valid session claims are not detected.
Accessing Claims
Use clerk.SessionClaimsFromContext(r.Context()) to retrieve the claims within your handler.
import (
"fmt"
"net/http"
"github.com/clerk/clerk-sdk-go/v2"
clerkhttp "github.com/clerk/clerk-sdk-go/v2/http"
)
func main() {
clerk.SetKey("sk_live_XXX")
mux := http.NewServeMux()
mux.HandleFunc("/", publicRoute)
// Protect this route
protectedHandler := http.HandlerFunc(protectedRoute)
mux.Handle("/protected", clerkhttp.WithHeaderAuthorization()(protectedHandler))
http.ListenAndServe(":3000", mux)
}
func protectedRoute(w http.ResponseWriter, r *http.Request) {
claims, ok := clerk.SessionClaimsFromContext(r.Context())
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
fmt.Fprintf(w, "{\"user_id\": \"%s\"}", claims.Subject)
}