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

# Secure Beego APIs with API Key Authentication

Secure your Beego API using a shared secret.

## How Zuplo Handles It

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

## Beego Backend Code

```go
package main

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

	beego "github.com/beego/beego/v2/server/web"
)

// SecretFilter is a filter that validates a shared secret from the request headers
var SecretFilter = func(ctx *beego.Context) {
	secret := ctx.Input.Header("X-Shared-Secret")
	expectedSecret := os.Getenv("SHARED_SECRET")

	if expectedSecret == "" {
		ctx.Output.SetStatus(http.StatusInternalServerError)
		ctx.Output.JSON(map[string]string{"error": "Server configuration error"}, false, false)
		return
	}

	if secret == "" {
		ctx.Output.SetStatus(http.StatusUnauthorized)
		ctx.Output.JSON(map[string]string{"error": "No secret provided"}, false, false)
		return
	}

	// Use timing-safe comparison to prevent timing attacks
	if subtle.ConstantTimeCompare([]byte(secret), []byte(expectedSecret)) == 0 {
		ctx.Output.SetStatus(http.StatusUnauthorized)
		ctx.Output.JSON(map[string]string{"error": "Invalid secret"}, false, false)
		return
	}

	// Continue to the next handler
}

// ProtectedController is a sample controller that requires authorization
type ProtectedController struct {
	beego.Controller
}

func (c *ProtectedController) Get() {
	c.Data["json"] = map[string]string{"message": "Access granted"}
	c.ServeJSON()
}

func main() {
	beego.InsertFilter("*", beego.BeforeRouter, SecretFilter)

	beego.Router("/protected", &ProtectedController{})

	beego.Run()
}
```

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