1

I'm really new to web development and I'm stuck trying to implement a simple HTTP auth in a project using actix-web. My needs are following:

  • I don't want/need any databases for the auth. It's enough for me to access the username and pass from enviroment variables, which will be provided when the docker container is run.

  • I just need authentication for the /api/* routes. All the other routes should stay public.

  • Ideally, it should be done using basic HTTP auth and stored in session.

I tried to use the actix_web_httpauth crate but I couldn't find enough documentation to implement in for my usecase.

Again, this is probably an easy thing to do, but I'm not at all familiar with web development. Any help is appreciated.

2 Answers 2

1

Yes, the examples in actix-web-httpauth are a little thin, but it's not a huge amount of code to get, say, a static username/password going:

use actix_web::{ dev::ServiceRequest, error::ErrorUnauthorized, web, App as ActixApp, Error as ActixError, HttpServer, }; use actix_web_httpauth::{extractors::basic::BasicAuth, middleware::HttpAuthentication}; async fn do_auth( req: ServiceRequest, creds: BasicAuth, ) -> Result<ServiceRequest, (ActixError, ServiceRequest)> { if creds.user_id() == "user" && creds.password() == Some("hunter2") { Ok(req) } else { Err((ErrorUnauthorized("nope"), req)) } } #[actix_web::main] async fn main() { HttpServer::new(|| { ActixApp::new() .wrap(HttpAuthentication::basic(do_auth)) .service(web::resource("/index.html").to(|| async { "Hello world!" })) }) .bind(("127.0.0.1", 8080)) .unwrap() .run() .await; } 
Sign up to request clarification or add additional context in comments.

Comments

0

I ended up using the actix-session to build a custom solution.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.