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

# Secure Sinatra APIs with API Key Authentication

Secure your Sinatra API using a shared secret.

## How Zuplo Handles It

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

## Sinatra Backend Code

```ruby
require 'sinatra'
require 'rack/utils'

# Middleware to validate shared secret header
before do
  secret = request.env["HTTP_X_SHARED_SECRET"]
  expected_secret = ENV['SHARED_SECRET']

  if expected_secret.nil?
    halt 500, { error: 'Server configuration error' }.to_json
  end

  if secret.nil?
    halt 401, { error: 'No secret provided' }.to_json
  end

  # Use Rack::Utils.secure_compare to prevent timing attacks
  unless Rack::Utils.secure_compare(secret, expected_secret)
    halt 401, { error: 'Invalid secret' }.to_json
  end
end

# Example protected route
get '/protected' do
  content_type :json
  { message: 'Access granted' }.to_json
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)
