---
title: "Secure ServiceStack APIs with API Key Authentication"
description: "Secure your ServiceStack API using a shared secret."
canonicalUrl: "https://zuplo.com/use-cases/api-key-auth/csharp/servicestack/secure-header"
framework: "ServiceStack"
language: "C#"
authStrategy: "shared secret header"
pageType: use-case
---

# Secure ServiceStack APIs with API Key Authentication

Secure your ServiceStack API using a shared secret.

## How Zuplo Handles It

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

## ServiceStack Backend Code

```csharp
using ServiceStack;
using ServiceStack.Web;
using System;
using System.Threading.Tasks;

public class SharedSecretFilter : RequestFilterAsyncAttribute
{
    public override async Task ExecuteAsync(IRequest req, IResponse res, object requestDto)
    {
        var secret = req.Headers["x-shared-secret"];
        var expectedSecret = Environment.GetEnvironmentVariable("SHARED_SECRET");

        if (string.IsNullOrEmpty(expectedSecret))
        {
            await res.WriteErrorAsync("Server configuration error", HttpStatusCode.InternalServerError);
            return;
        }

        if (string.IsNullOrEmpty(secret))
        {
            await res.WriteErrorAsync("No secret provided", HttpStatusCode.Unauthorized);
            return;
        }

        if (!SecureCompare(secret, expectedSecret))
        {
            await res.WriteErrorAsync("Invalid secret", HttpStatusCode.Unauthorized);
            return;
        }

        await Task.CompletedTask;
    }

    private bool SecureCompare(string a, string b)
    {
        if (a.Length != b.Length) return false;

        int result = 0;
        for (int i = 0; i < a.Length; i++)
        {
            result |= a[i] ^ b[i];
        }

        return result == 0;
    }
}

public class ProtectedService : Service
{
    [SharedSecretFilter]
    public object Any(ProtectedRequest request)
    {
        return new { message = "Access granted" };
    }
}

[Route("/protected")]
public class ProtectedRequest : IReturn<object>
{
}
```

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