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

# Secure Gin APIs with API Key Authentication

Secure your Gin API using a shared secret.

## How Zuplo Handles It

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

## Gin Backend Code

```go
package main

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

	"github.com/gin-gonic/gin"
)

// validateSharedSecret middleware to validate shared secret header
func validateSharedSecret() gin.HandlerFunc {
	return func(c *gin.Context) {
		secret := c.GetHeader("X-Shared-Secret")
		expectedSecret := os.Getenv("SHARED_SECRET")

		if expectedSecret == "" {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Server configuration error"})
			c.Abort()
			return
		}

		if secret == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "No secret provided"})
			c.Abort()
			return
		}

		// Use timing-safe comparison to prevent timing attacks
		if subtle.ConstantTimeCompare([]byte(secret), []byte(expectedSecret)) != 1 {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid secret"})
			c.Abort()
			return
		}

		c.Next()
	}
}

func main() {
	r := gin.Default()

	r.GET("/protected", validateSharedSecret(), func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"message": "Access granted"})
	})

	if err := r.Run(":8080"); err != nil {
		fmt.Printf("Server failed to start: %v\n", err)
	}
}
```

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