Zuplo

API Key Authentication

Secure Your Gorilla Mux API with API Keys

The Zuplo API Gateway protects your backend API from unauthorized access, abuse, and overload. Add API key authentication to your Gorilla Mux API in minutes.

Secure Access

Authenticate every request before it reaches your backend.

Control Costs

Set rate limits and quotas to prevent runaway usage.

Ensure Reliability

Shield your backend from overload with traffic management.

How it works

The Zuplo API Gateway sits between your clients and your Gorilla Mux backend, providing a secure layer of protection and control.

Client
Zuplo API Gateway

Customer VPC

Backend

Step-by-step tutorial

It takes only a few minutes to put Zuplo in front of your Gorilla Mux backend, adding API key authentication, and configuring your origin to trust requests from Zuplo using JWT verification.

1

Create a Route in Zuplo

First, create a new route in your Zuplo project that will proxy requests to your Gorilla Mux backend. This route will be the entry point for your API consumers.

Creating a route in Zuplo
Learn how to create routes

📄 OpenAPI native. Import your existing OpenAPI spec to instantly create routes and power your API documentation .

2

Add API Key Authentication Policy

Add the API Key Authentication policy to your route. This policy validates incoming API keys and ensures only authorized consumers can access your API.

Adding API Key Authentication policy in Zuplo
API Key Authentication docs

🔐 Leaked key? No problem. As a GitHub Secret Scanning partner, Zuplo can automatically revoke exposed keys before they can be exploited.

3

Enable the JWT Service Plugin

Enable the JWT Service Plugin in your Zuplo project. This plugin generates JWTs that your origin API can validate, creating a secure trust relationship between Zuplo and your backend.

TypeScriptmodules/zuplo.runtime.ts
export function runtimeInit(runtime: RuntimeExtensions) {
  // Register the JWT Service Plugin
  runtime.addPlugin(new JwtServicePlugin());
}
JWT Service Plugin docs
4

Secure Your Gorilla Mux API with JWT Authentication

Configure your Gorilla Mux backend to validate the JWTs issued by Zuplo. This ensures that only requests coming through your Zuplo gateway are accepted.

Go
package main

import (
    "fmt"
    "github.com/golang-jwt/jwt/v4"
    "github.com/gorilla/mux"
    "log"
    "net/http"
    "strings"
    "github.com/MicahParks/keyfunc"
)

const (
    issuer = "https://my-api-a32f34.zuplo.api/__zuplo/issuer"
)

var (
    keyFunc *keyfunc.JWKS
)

func init() {
    jwksURL := fmt.Sprintf("%s/.well-known/jwks.json", issuer)
    options := keyfunc.Options{
        RefreshErrorHandler: func(err error) {
            log.Printf("There was an error with the jwt.Keyfunc\nError:%s\n", err.Error())
        },
    }

    var err error
    keyFunc, err = keyfunc.Get(jwksURL, options)
    if err != nil {
        log.Fatalf("Failed to create JWKS from URL: %s\nError: %s", jwksURL, err.Error())
    }
}

func validateJWT(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        authHeader := r.Header.Get("Authorization")
        if authHeader == "" {
            http.Error(w, "No token provided", http.StatusUnauthorized)
            return
        }

        tokenString := strings.TrimPrefix(authHeader, "Bearer ")
        token, err := jwt.Parse(tokenString, keyFunc.Keyfunc)
        if err != nil || !token.Valid {
            http.Error(w, "Invalid token", http.StatusUnauthorized)
            return
        }

        claims, ok := token.Claims.(jwt.MapClaims)
        if !ok || !token.Valid {
            http.Error(w, "Invalid token claims", http.StatusUnauthorized)
            return
        }

        if claims["iss"] != issuer {
            http.Error(w, "Invalid issuer", http.StatusUnauthorized)
            return
        }

        // Pass user info to context
        r = r.WithContext(context.WithValue(r.Context(), "user", claims))
        next.ServeHTTP(w, r)
    })
}

func protectedEndpoint(w http.ResponseWriter, r *http.Request) {
    user := r.Context().Value("user")
    response := fmt.Sprintf("Access granted. User: %v", user)
    w.Write([]byte(response))
}

func main() {
    r := mux.NewRouter()

    // Protected Route
    r.Handle("/protected", validateJWT(http.HandlerFunc(protectedEndpoint)))

    http.Handle("/", r)
    log.Println("Server listening on :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}
5

Call Your API Through Zuplo

Now you can call your API through Zuplo using an API key. The request will be authenticated at the gateway, and a JWT will be forwarded to your Gorilla Mux backend.

Terminalbash
curl -X GET \
  'https://your-api.zuplo.dev/your-route' \
  -H 'Authorization: Bearer YOUR_API_KEY'

Ready to secure your API?

Get started with Zuplo for free and add API key authentication to your Gorilla Mux API in minutes.