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

# Secure Ruby on Rails APIs with API Key Authentication

Secure your Ruby on Rails API using a shared secret.

## How Zuplo Handles It

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

## Ruby on Rails Backend Code

```ruby
# config/initializers/shared_secret_middleware.rb

class SharedSecretMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    request = Rack::Request.new(env)
    secret = request.get_header("HTTP_X_SHARED_SECRET")
    expected_secret = ENV['SHARED_SECRET']

    # Check if the expected secret is configured
    unless expected_secret
      return [500, { "Content-Type" => "application/json" }, [{ error: "Server configuration error" }.to_json]]
    end

    # Validate the provided secret
    if secret.nil? || !ActiveSupport::SecurityUtils.secure_compare(secret, expected_secret)
      return [401, { "Content-Type" => "application/json" }, [{ error: "Invalid or missing secret" }.to_json]]
    end

    @app.call(env)
  end
end

# Add the middleware to your application
# config/application.rb
module YourApp
  class Application < Rails::Application
    config.middleware.use SharedSecretMiddleware
  end
end

# Example protected route in a controller
# app/controllers/protected_controller.rb
class ProtectedController < ApplicationController
  def show
    render json: { message: "Access granted" }
  end
end

# config/routes.rb
Rails.application.routes.draw do
  get '/protected', to: 'protected#show'
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)
