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

# Secure Rocket APIs with API Key Authentication

Secure your Rocket API using a shared secret.

## How Zuplo Handles It

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

## Rocket Backend Code

```rust
use rocket::http::Status;
use rocket::request::{self, FromRequest, Request};
use rocket::{get, routes, Build, Rocket};
use rocket::outcome::Outcome;
use subtle::ConstantTimeEq; // To perform timing safe comparisons
use std::env;

// Guard for validating the shared secret
struct ValidateSharedSecret;

#[rocket::async_trait]
impl<'r> FromRequest<'r> for ValidateSharedSecret {
    type Error = ();

    async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
        let secret = request.headers().get_one("x-shared-secret");
        let expected_secret = env::var("SHARED_SECRET").ok();

        match (secret, expected_secret) {
            (Some(secret), Some(expected_secret)) => {
                if secret.len() != expected_secret.len() ||
                   !secret.as_bytes().ct_eq(expected_secret.as_bytes()).into() {
                    Outcome::Failure((Status::Unauthorized, ()))
                } else {
                    Outcome::Success(ValidateSharedSecret)
                }
            },
            (None, _) => Outcome::Failure((Status::Unauthorized, ())),
            _ => Outcome::Failure((Status::InternalServerError, ())),
        }
    }
}

#[get("/protected")]
fn protected_route(_auth: ValidateSharedSecret) -> &'static str {
    "Access granted"
}

#[launch]
fn rocket() -> Rocket<Build> {
    rocket::build()
        .mount("/", routes![protected_route])
}
```

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