---
title: "Secure undefined APIs with API Key Authentication"
description: undefined
canonicalUrl: "https://zuplo.com/use-cases/api-key-auth/ruby/cuba/secure-header"
framework: undefined
language: undefined
authStrategy: "shared secret header"
pageType: use-case
---

# Secure undefined APIs with API Key Authentication



## How Zuplo Handles It

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

## undefined Backend Code

```ruby
require "cuba"
require "rack/protection"
require "openssl"

# Middleware to validate shared secret
module ValidateSharedSecret
  def self.call(env)
    request = Rack::Request.new(env)

    secret = request.env["HTTP_X_SHARED_SECRET"]
    expected_secret = ENV["SHARED_SECRET"]

    halt_with_500 unless expected_secret

    halt_with_401("No secret provided") unless secret
    halt_with_401("Invalid secret") unless valid_secret?(secret, expected_secret)

    yield
  end

  def self.halt_with_500
    [500, { "Content-Type" => "application/json" }, [{ error: "Server configuration error" }.to_json]]
  end

  def self.halt_with_401(message)
    [401, { "Content-Type" => "application/json" }, [{ error: message }.to_json]]
  end

  def self.valid_secret?(secret, expected_secret)
    return false if secret.bytesize != expected_secret.bytesize

    secure_compare(secret, expected_secret)
  end

  def self.secure_compare(a, b)
    OpenSSL.fixed_length_secure_compare(a, b)
  end
end

Cuba.define do
  on "protected" do
    on ValidateSharedSecret do
      res.headers["Content-Type"] = "application/json"
      res.write({ message: "Access granted" }.to_json)
    end
  end
end
```

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