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

# Secure NancyFX APIs with API Key Authentication

Secure your NancyFX API using a shared secret.

## How Zuplo Handles It

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

## NancyFX Backend Code

```csharp
using System;
using System.Security.Cryptography;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.TinyIoc;

public class SecureModule : NancyModule
{
    public SecureModule()
    {
        // Use the middleware to secure this route
        Before += ValidateSharedSecret;

        Get("/protected", _ =>
        {
            return Response.AsJson(new { message = "Access granted" });
        });
    }

    private Response ValidateSharedSecret(NancyContext context)
    {
        var secretHeader = context.Request.Headers["x-shared-secret"];
        var expectedSecret = Environment.GetEnvironmentVariable("SHARED_SECRET");

        if (string.IsNullOrWhiteSpace(expectedSecret))
        {
            return HttpStatusCode.InternalServerError.WithReasonPhrase("Server configuration error");
        }

        if (string.IsNullOrWhiteSpace(secretHeader))
        {
            return HttpStatusCode.Unauthorized.WithReasonPhrase("No secret provided");
        }

        var secret = secretHeader.Single();

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

        return null;
    }

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

        using (var hmac = new HMACSHA256())
        {
            var hashA = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(a));
            var hashB = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(b));

            return CryptographicOperations.FixedTimeEquals(hashA, hashB);
        }
    }
}

public class Bootstrapper : DefaultNancyBootstrapper
{
    protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
    {
        base.ApplicationStartup(container, pipelines);
        // Apply other configurations here if needed
    }
}
```

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