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

# Secure Chi APIs with API Key Authentication

Secure your Chi API using a shared secret.

## How Zuplo Handles It

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

## Chi Backend Code

```go
package main

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

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
)

// 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
		}

		if subtle.ConstantTimeCompare([]byte(secret), []byte(expectedSecret)) != 1 {
			http.Error(w, "Invalid secret", http.StatusUnauthorized)
			return
		}

		next.ServeHTTP(w, r)
	})
}

func main() {
	r := chi.NewRouter()
	r.Use(middleware.Logger)

	// Protected route
	r.Route("/protected", func(r chi.Router) {
		r.Use(validateSharedSecret)
		r.Get("/", func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte(`{"message": "Access granted"}`))
		})
	})

	log.Fatal(http.ListenAndServe(":8080", r))
}
```

## 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)
