Zuplo

API Key Authentication

Secure Your Beego API with API Keys

The Zuplo API Gateway protects your backend API from unauthorized access, abuse, and overload. Add API key authentication to your Beego API in minutes.

Secure Access

Authenticate every request before it reaches your backend.

Control Costs

Set rate limits and quotas to prevent runaway usage.

Ensure Reliability

Shield your backend from overload with traffic management.

How it works

The Zuplo API Gateway sits between your clients and your Beego backend, providing a secure layer of protection and control.

Client
Zuplo API Gateway

Customer VPC

Backend

Step-by-step tutorial

It takes only a few minutes to put Zuplo in front of your Beego backend, adding API key authentication, and configuring your origin to trust requests from Zuplo using JWT verification.

1

Create a Route in Zuplo

First, create a new route in your Zuplo project that will proxy requests to your Beego backend. This route will be the entry point for your API consumers.

Creating a route in Zuplo
Learn how to create routes

📄 OpenAPI native. Import your existing OpenAPI spec to instantly create routes and power your API documentation .

2

Add API Key Authentication Policy

Add the API Key Authentication policy to your route. This policy validates incoming API keys and ensures only authorized consumers can access your API.

Adding API Key Authentication policy in Zuplo
API Key Authentication docs

🔐 Leaked key? No problem. As a GitHub Secret Scanning partner, Zuplo can automatically revoke exposed keys before they can be exploited.

3

Enable the JWT Service Plugin

Enable the JWT Service Plugin in your Zuplo project. This plugin generates JWTs that your origin API can validate, creating a secure trust relationship between Zuplo and your backend.

TypeScriptmodules/zuplo.runtime.ts
export function runtimeInit(runtime: RuntimeExtensions) {
  // Register the JWT Service Plugin
  runtime.addPlugin(new JwtServicePlugin());
}
JWT Service Plugin docs
4

Secure Your Beego API with JWT Authentication

Configure your Beego backend to validate the JWTs issued by Zuplo. This ensures that only requests coming through your Zuplo gateway are accepted.

Go
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"strings"

	"github.com/astaxie/beego"
	"github.com/dgrijalva/jwt-go"
	"gopkg.in/square/go-jose.v2/jwk"
)

// Constants
const Issuer = "https://my-api-a32f34.zuplo.api/__zuplo/issuer"
const JwksURL = Issuer + "/.well-known/jwks.json"

// JWKSClient fetches and caches the JWKS
type JWKSClient struct {
	jwks *jwk.Set
}

// NewJWKSClient initializes the JWKS client with caching logic
func NewJWKSClient() (*JWKSClient, error) {
	resp, err := http.Get(JwksURL)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var jwks jwk.Set
	if err := json.NewDecoder(resp.Body).Decode(&jwks); err != nil {
		return nil, err
	}

	return &JWKSClient{jwks: &jwks}, nil
}

// GetKey retrieves the public key by kid
func (j *JWKSClient) GetKey(kid string) (interface{}, error) {
	keys := j.jwks.LookupKeyID(kid)
	if len(keys) == 0 {
		return nil, errors.New("key not found")
	}
	publicKey, err := keys[0].Materialize()
	if err != nil {
		return nil, err
	}
	return publicKey, nil
}

// JWTMiddleware validates the JWT token
func JWTMiddleware(jwksClient *JWKSClient) beego.FilterFunc {
	return func(ctx *context.Context) {
		authHeader := ctx.Input.Header("Authorization")
		if authHeader == "" {
			ctx.Output.SetStatus(http.StatusUnauthorized)
			ctx.Output.Body([]byte("No token provided"))
			return
		}

		tokenString := strings.TrimPrefix(authHeader, "Bearer ")
		token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
			// Check the signing method
			if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
				return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
			}

			kid, ok := token.Header["kid"].(string)
			if !ok {
				return nil, errors.New("kid not found in token header")
			}

			return jwksClient.GetKey(kid)
		})
		if err != nil {
			ctx.Output.SetStatus(http.StatusUnauthorized)
			ctx.Output.Body([]byte("Invalid token: " + err.Error()))
			return
		}

		if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
			// Access your claims here if needed
			ctx.Input.SetData("user", claims)
		} else {
			ctx.Output.SetStatus(http.StatusUnauthorized)
			ctx.Output.Body([]byte("Invalid token claims"))
		}
	}
}

func main() {
	// Initialize JWKS Client
	jwksClient, err := NewJWKSClient()
	if err != nil {
		panic("Failed to initialize JWKS client: " + err.Error())
	}

	// Register the JWT middleware
	beego.InsertFilter("/protected/*", beego.BeforeRouter, JWTMiddleware(jwksClient))

	// Add a protected route
	beego.Router("/protected/data", &ProtectedController{})

	// Run the server
	beego.Run()
}

// ProtectedController handles requests to protected routes
type ProtectedController struct {
	beego.Controller
}

func (p *ProtectedController) Get() {
	user := p.Ctx.Input.GetData("user")
	p.Data["json"] = map[string]interface{}{
		"message": "Access granted",
		"user":    user,
	}
	p.ServeJSON()
}
5

Call Your API Through Zuplo

Now you can call your API through Zuplo using an API key. The request will be authenticated at the gateway, and a JWT will be forwarded to your Beego backend.

Terminalbash
curl -X GET \
  'https://your-api.zuplo.dev/your-route' \
  -H 'Authorization: Bearer YOUR_API_KEY'

Ready to secure your API?

Get started with Zuplo for free and add API key authentication to your Beego API in minutes.