Zuplo

API Key Authentication

Secure Your Salvo API with API Keys

The Zuplo API Gateway protects your backend API from unauthorized access, abuse, and overload. Add API key authentication to your Salvo 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 Salvo 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 Salvo 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 Salvo 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 Salvo API with JWT Authentication

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

Rust
use salvo::prelude::*;
use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
use reqwest::Client;
use std::sync::Arc;
use tokio::sync::RwLock;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::error;

const ISSUER: &str = "https://my-api-a32f34.zuplo.api/__zuplo/issuer";
const JWKS_URI: &str = "https://my-api-a32f34.zuplo.api/__zuplo/issuer/.well-known/jwks.json";

#[derive(Debug, Deserialize)]
struct Jwk {
    kid: String,
    n: String,
    e: String,
}

#[derive(Debug, Deserialize)]
struct Jwks {
    keys: Vec<Jwk>,
}

#[derive(Debug, Serialize, Deserialize)]
struct Claims {
    sub: String,
    exp: usize,
}

async fn fetch_jwks() -> Result<Jwks, reqwest::Error> {
    let client = Client::new();
    let resp = client.get(JWKS_URI).send().await?;
    Ok(resp.json::<Jwks>().await?)
}

async fn validate_token(token: &str, jwks: &Jwks) -> Result<Claims, String> {
    let header = decode_header(token).map_err(|e| format!("Decode error: {:?}", e))?;
    let kid = match header.kid {
        Some(kid) => kid,
        None => return Err("No `kid` found in token header".into()),
    };

    let jwk = jwks.keys.iter().find(|j| j.kid == kid).ok_or("No matching JWK found")?;
    let decoding_key = DecodingKey::from_rsa_components(&jwk.n, &jwk.e)
        .map_err(|e| format!("Decoding key error: {:?}", e))?;

    let mut validation = Validation::new(Algorithm::RS256);
    validation.set_issuer(&[ISSUER]);

    let data = decode::<Claims>(token, &decoding_key, &validation)
        .map_err(|e| format!("Token decode error: {:?}", e))?;

    Ok(data.claims)
}

struct JwtGuard {
    jwks: Arc<RwLock<Jwks>>,
}

#[async_trait]
impl Handler for JwtGuard {
    async fn handle(&self, req: &mut Request, res: &mut Response) {
        if let Some(auth_header) = req.header::<String>("authorization") {
            if let Some(token) = auth_header.strip_prefix("Bearer ") {
                let jwks_guard = self.jwks.read().await;
                match validate_token(token, &jwks_guard).await {
                    Ok(claims) => {
                        req.extensions_mut().insert(claims);
                        return;
                    }
                    Err(err) => {
                        error!("Token validation error: {}", err);
                        res.set_status_code(StatusCode::UNAUTHORIZED);
                        res.render(Text::Plain("Invalid token".into()));
                        return;
                    }
                };
            }
        }
        res.set_status_code(StatusCode::UNAUTHORIZED);
        res.render(Text::Plain("No token provided".into()));
    }
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt().init();

    let jwks = fetch_jwks().await.expect("Failed to fetch JWKS");
    let jwks = Arc::new(RwLock::new(jwks));

    let router = Router::new()
        .hoop(JwtGuard { jwks: jwks.clone() })
        .handle(protected);

    Server::new(TcpListener::bind("127.0.0.1:7878"))
        .serve(router)
        .await;
}

#[fn_handler]
async fn protected(req: &mut Request, res: &mut Response) {
    if let Some(claims) = req.extensions().get::<Claims>() {
        res.render(Json(claims));
    } else {
        res.set_status_code(StatusCode::UNAUTHORIZED);
        res.render(Text::Plain("Unauthorized".into()));
    }
}
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 Salvo 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 Salvo API in minutes.