Rocket Cors & Headers
ynhhoJ opened this issue · comments
Hi!
Where i can find an example where is used Rocket Cors & Headers to prevent access to some API's?
Example:
use rocket_cors::{Guard};
#[get("/sensitive")]
pub fn sensitive(cors: Guard<'_>) -> rocket_cors::Responder<&str> {
// check if Headers api-key == my_secret_key
cors.responder("Sensitive content")
}
use rocket::http::Status;
use rocket::request::{Outcome, Request, FromRequest};
#[derive(Debug)]
pub struct ApiKey<'r>(&'r str);
#[derive(Debug)]
pub enum ApiKeyError {
Missing,
Invalid,
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for ApiKey<'r> {
type Error = ApiKeyError;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
/// Returns true if `key` is a valid API key string.
fn is_valid(key: &str) -> bool {
key == "valid_api_key"
}
match req.headers().get_one("x-api-key") {
None => Outcome::Failure((Status::BadRequest, ApiKeyError::Missing)),
Some(key) if is_valid(key) => Outcome::Success(ApiKey(key)),
Some(_) => Outcome::Failure((Status::BadRequest, ApiKeyError::Invalid)),
}
}
}
#[get("/sensitive")]
fn sensitive(key: ApiKey<'_>, cors: Guard<'_>) -> rocket_cors::Responder<&'static str> {
cors.responder("Sensitive data.")
}
Example based on: https://docs.rs/rocket/0.5.0-rc.1/rocket/request/trait.FromRequest.html#example-1