---
title: "Secure Actix Web APIs with API Key Authentication"
description: "Secure your Actix Web API using a shared secret."
canonicalUrl: "https://zuplo.com/use-cases/api-key-auth/rust/actixweb/secure-header"
framework: "Actix Web"
language: "Rust"
authStrategy: "shared secret header"
pageType: use-case
---

# Secure Actix Web APIs with API Key Authentication

Secure your Actix Web API using a shared secret.

## How Zuplo Handles It

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

## Actix Web Backend Code

```rust
use actix_web::{dev::ServiceRequest, middleware, web, App, Error, HttpResponse, HttpServer, Result};
use actix_web::error::ErrorUnauthorized;
use futures::future::{ok, Ready};
use std::env;
use std::sync::Arc;
use subtle::ConstantTimeEq;

// Middleware to validate shared secret header
async fn validate_shared_secret(req: ServiceRequest, srv: &web::ServiceConfig) -> Result<ServiceRequest, Error> {
    let expected_secret = env::var("SHARED_SECRET").map_err(|_| {
        actix_web::error::ErrorInternalServerError("Server configuration error")
    })?;

    let headers = req.headers();
    let secret_header = headers.get("x-shared-secret").ok_or_else(|| {
        ErrorUnauthorized("No secret provided")
    })?;

    if secret_header.as_bytes().ct_eq(expected_secret.as_bytes()).unwrap_u8() == 1 {
        Ok(req)
    } else {
        Err(ErrorUnauthorized("Invalid secret"))
    }
}

// Example usage
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // Ensure the expected secret is set before starting the server
    env::set_var("SHARED_SECRET", "your_shared_secret");

    HttpServer::new(|| {
        App::new()
            .wrap(middleware::Compat::new(validate_shared_secret))
            .route("/protected", web::get().to(protected))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

async fn protected() -> HttpResponse {
    HttpResponse::Ok().json("Access granted")
}
```

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