---
title: "Secure Gorilla Mux APIs with API Key Authentication"
description: "Secure your Gorilla Mux API using a shared secret."
canonicalUrl: "https://zuplo.com/use-cases/api-key-auth/go/gorillamux/secure-header"
framework: "Gorilla Mux"
language: "Go"
authStrategy: "shared secret header"
pageType: use-case
---

# Secure Gorilla Mux APIs with API Key Authentication

Secure your Gorilla Mux API using a shared secret.

## How Zuplo Handles It

Put Zuplo in front of your Gorilla Mux backend to authenticate API keys and forward a shared secret header so your origin only accepts traffic from Zuplo.

## Gorilla Mux Backend Code

```go
package main

import (
	"crypto/subtle"
	"log"
	"net/http"
	"os"

	"github.com/gorilla/mux"
)

// Middleware to validate shared secret header
func validateSharedSecret(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		secret := r.Header.Get("X-Shared-Secret")
		expectedSecret := os.Getenv("SHARED_SECRET")

		if expectedSecret == "" {
			http.Error(w, "Server configuration error", http.StatusInternalServerError)
			return
		}

		if secret == "" {
			http.Error(w, "No secret provided", http.StatusUnauthorized)
			return
		}

		// Use constant time comparison to prevent timing attacks
		if subtle.ConstantTimeCompare([]byte(secret), []byte(expectedSecret)) != 1 {
			http.Error(w, "Invalid secret", http.StatusUnauthorized)
			return
		}

		next.ServeHTTP(w, r)
	})
}

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

	// Protected route example
	r.Handle("/protected", validateSharedSecret(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(`{"message": "Access granted"}`))
	}))).Methods("GET")

	http.Handle("/", r)

	log.Println("Server running on :8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}
```

## Example Request

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

## Learn More

- [API Key Authentication on Zuplo](https://zuplo.com/docs/policies/api-key-auth-inbound)
- [JWT Authentication on Zuplo](https://zuplo.com/docs/policies/open-id-jwt-auth-inbound)
- [All use cases](https://zuplo.com/use-cases)
