Skip to content

Instantly share code, notes, and snippets.

@skanehira
Last active May 27, 2023 01:19
Show Gist options
  • Save skanehira/9c7fa86e3a2f78a0c7131a701c84e79c to your computer and use it in GitHub Desktop.
Save skanehira/9c7fa86e3a2f78a0c7131a701c84e79c to your computer and use it in GitHub Desktop.
axum + basic auth
[package]
name = "auth"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
axum = { version = "0.6.18", features = ["headers"] }
tokio = { version = "1", features = ["full", "macros", "rt-multi-thread"] }
use axum::{
body::Body,
extract::TypedHeader,
headers::{authorization::Basic, Authorization},
http::{header, Request, StatusCode},
middleware::{self, Next},
response::Response,
routing::get,
RequestPartsExt, Router,
};
macro_rules! unauthorized {
() => {
let resp = Response::builder()
.status(StatusCode::UNAUTHORIZED)
.header(header::WWW_AUTHENTICATE, "Basic realm=\"Secure Area\"")
.body(axum::body::boxed(Body::empty()))
.unwrap();
return resp;
};
}
async fn auth_middleware<B>(req: Request<B>, next: Next<B>) -> Response {
let (mut parts, body) = req.into_parts();
let auth = parts.extract::<TypedHeader<Authorization<Basic>>>().await;
match auth {
Ok(auth) => {
if auth.username() != "user" || auth.password() != "pass" {
// invalid user
unauthorized!();
}
}
Err(e) => {
// no auth header
eprintln!("{}", e);
unauthorized!();
}
}
let req = Request::from_parts(parts, body);
next.run(req).await
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello))
.layer(middleware::from_fn(auth_middleware));
let server =
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()).serve(app.into_make_service());
if let Err(err) = server.await {
eprintln!("Server error: {}", err);
}
}
async fn hello() {
println!("Hello")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment