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

# Secure Buffalo APIs with API Key Authentication

Secure your Buffalo API using a shared secret.

## How Zuplo Handles It

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

## Buffalo Backend Code

```go
package main

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

	"github.com/gobuffalo/buffalo"
)

// Middleware to validate shared secret header
func validateSharedSecret(next buffalo.Handler) buffalo.Handler {
	return func(c buffalo.Context) error {
		secret := c.Request().Header.Get("X-Shared-Secret")
		expectedSecret := os.Getenv("SHARED_SECRET")

		if expectedSecret == "" {
			return c.Error(http.StatusInternalServerError, errors.New("server configuration error"))
		}

		if secret == "" {
			return c.Render(http.StatusUnauthorized, r.JSON(map[string]string{"error": "No secret provided"}))
		}

		// Use subtle.ConstantTimeCompare for timing-safe comparison
		if len(secret) != len(expectedSecret) ||
		   subtle.ConstantTimeCompare([]byte(secret), []byte(expectedSecret)) != 1 {
			return c.Render(http.StatusUnauthorized, r.JSON(map[string]string{"error": "Invalid secret"}))
		}

		return next(c)
	}
}

func main() {
	app := buffalo.New(buffalo.Options{
		Env:         "development",
		SessionName: "_buffalo_session",
	})

	// Protected route example
	app.GET("/protected", validateSharedSecret(func(c buffalo.Context) error {
		return c.Render(http.StatusOK, r.JSON(map[string]string{"message": "Access granted"}))
	}))

	app.Start(":3000")
}
```

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