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

# Secure GoFr APIs with API Key Authentication

Secure your GoFr API using a shared secret.

## How Zuplo Handles It

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

## GoFr Backend Code

```go
package main

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

	"github.com/goframework/gofr/app"
	"github.com/goframework/gofr/http/middleware"
	"github.com/goframework/gofr/http/response"
)

// SharedSecretMiddleware checks for the shared secret in the request header.
func SharedSecretMiddleware(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 == "" {
			response.JSON(w, http.StatusInternalServerError, map[string]string{"error": "Server configuration error"})
			return
		}

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

		// Use constant time comparison to prevent timing attacks
		if len(secret) != len(expectedSecret) || subtle.ConstantTimeCompare([]byte(secret), []byte(expectedSecret)) != 1 {
			response.JSON(w, http.StatusUnauthorized, map[string]string{"error": "Invalid secret"})
			return
		}

		next.ServeHTTP(w, r)
	})
}

func main() {
	application := app.New()

	// Register the middleware globally or to specific routes
	application.Use(SharedSecretMiddleware)

	// Example protected route
	application.HandleFunc("/protected", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		response.JSON(w, http.StatusOK, map[string]string{"message": "Access granted"})
	})

	application.ListenAndServe(":8080")
}
```

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