1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-27 17:22:57 +01:00
actix-extras/actix-web-httpauth/examples/middleware.rs

58 lines
1.6 KiB
Rust
Raw Permalink Normal View History

2024-06-11 04:52:45 +02:00
use actix_web::{
dev::ServiceRequest, error, get, middleware::Logger, App, Error, HttpServer, Responder,
};
use actix_web_httpauth::{extractors::bearer::BearerAuth, middleware::HttpAuthentication};
use tracing::level_filters::LevelFilter;
use tracing_subscriber::EnvFilter;
2024-06-11 04:52:45 +02:00
/// Validator that:
/// - accepts Bearer auth;
/// - returns a custom response for requests without a valid Bearer Authorization header;
/// - rejects tokens containing an "x" (for quick testing using command line HTTP clients).
async fn validator(
req: ServiceRequest,
2024-06-11 04:52:45 +02:00
credentials: Option<BearerAuth>,
) -> Result<ServiceRequest, (Error, ServiceRequest)> {
2024-06-11 04:52:45 +02:00
let Some(credentials) = credentials else {
return Err((error::ErrorBadRequest("no bearer header"), req));
};
eprintln!("{credentials:?}");
if credentials.token().contains('x') {
return Err((error::ErrorBadRequest("token contains x"), req));
}
2020-01-06 17:00:43 +01:00
Ok(req)
}
2024-06-11 04:52:45 +02:00
#[get("/")]
async fn index(auth: BearerAuth) -> impl Responder {
format!("authenticated for token: {}", auth.token().to_owned())
}
#[actix_web::main]
2020-01-06 17:00:43 +01:00
async fn main() -> std::io::Result<()> {
2024-06-11 04:52:45 +02:00
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env_lossy(),
)
.without_time()
.init();
HttpServer::new(|| {
2024-06-11 04:52:45 +02:00
let auth = HttpAuthentication::with_fn(validator);
App::new()
2024-06-11 04:52:45 +02:00
.service(index)
.wrap(auth)
2024-06-11 04:52:45 +02:00
.wrap(Logger::default().log_target("@"))
})
.bind("127.0.0.1:8080")?
2024-06-11 04:52:45 +02:00
.workers(2)
.run()
2020-01-06 17:00:43 +01:00
.await
}