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

# Secure Grape APIs with API Key Authentication

Secure your Grape API using a shared secret.

## How Zuplo Handles It

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

## Grape Backend Code

```ruby
require 'grape'
require 'rack/utils'
require 'openssl'

class API < Grape::API
  before do
    validate_shared_secret
  end

  helpers do
    def validate_shared_secret
      secret = headers['X-Shared-Secret']
      expected_secret = ENV['SHARED_SECRET']

      error!('Server configuration error', 500) unless expected_secret
      error!('No secret provided', 401) unless secret

      unless secure_compare(secret, expected_secret)
        error!('Invalid secret', 401)
      end
    end

    def secure_compare(a, b)
      return false unless a.bytesize == b.bytesize

      OpenSSL.secure_compare(a, b)
    end
  end

  resource :protected do
    get do
      { message: 'Access granted' }
    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)
