mirror of
https://github.com/actix/actix-extras.git
synced 2025-06-29 19:24:58 +02:00
Working version of the BasicAuth
This commit is contained in:
@ -1,25 +1,24 @@
|
||||
extern crate actix_web;
|
||||
extern crate actix_web_httpauth;
|
||||
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::{server, App, HttpRequest, FromRequest, Result};
|
||||
use actix_web::middleware::{Middleware, Started};
|
||||
use actix_web_httpauth::BasicAuth;
|
||||
use actix_web_httpauth::basic::{BasicAuth, Config};
|
||||
|
||||
struct AuthMiddleware;
|
||||
|
||||
impl<S> Middleware<S> for AuthMiddleware {
|
||||
fn start(&self, req: &mut HttpRequest<S>) -> Result<Started> {
|
||||
let auth = BasicAuth::extract(&req)?;
|
||||
let mut config = Config::default();
|
||||
config.realm("Restricted area".to_string());
|
||||
let auth = BasicAuth::from_request(&req, &config)?;
|
||||
|
||||
// Please note that this is only an example,
|
||||
// do not ever hardcode your credentials!
|
||||
if auth.username == "root" && auth.password == "pass" {
|
||||
Ok(Started::Done)
|
||||
} else {
|
||||
let response = req.build_response(StatusCode::UNAUTHORIZED)
|
||||
.header("WWW-Authenticate", "Basic")
|
||||
.finish();
|
||||
let response = BasicAuth::error_response(&config);
|
||||
Ok(Started::Response(response))
|
||||
}
|
||||
}
|
||||
@ -32,8 +31,8 @@ fn index(auth: BasicAuth) -> String {
|
||||
|
||||
fn main() {
|
||||
server::new(|| App::new()
|
||||
// Comment line below to pass authentication handling
|
||||
// directly to `index` handler.
|
||||
// Comment the `.middleware()` line and let `BasicAuth` extractor
|
||||
// in the `index` handler do the authentication routine
|
||||
.middleware(AuthMiddleware)
|
||||
.resource("/", |r| r.with(index)))
|
||||
.bind("127.0.0.1:8088").unwrap()
|
||||
|
Reference in New Issue
Block a user