mirror of
https://github.com/actix/actix-extras.git
synced 2024-11-23 23:51:06 +01:00
Support actix-web 2.x (#14)
This commit is contained in:
parent
f808e0680d
commit
d83cbc8542
10
Cargo.toml
10
Cargo.toml
@ -14,13 +14,15 @@ exclude = [".travis.yml", ".gitignore"]
|
|||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = { version = "^1.0", default_features = false }
|
actix-web = { version = "^2.0", default_features = false }
|
||||||
actix-service = "0.4.0"
|
actix-service = "1.0"
|
||||||
futures = "0.1"
|
futures = "0.3"
|
||||||
futures-locks = "0.3.3"
|
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
base64 = "0.10"
|
base64 = "0.10"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
actix-rt = "1.0"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = []
|
default = []
|
||||||
nightly = []
|
nightly = []
|
||||||
|
@ -1,18 +1,19 @@
|
|||||||
use actix_web::{middleware, web, App, HttpServer};
|
use actix_web::{middleware, web, App, HttpServer};
|
||||||
|
|
||||||
use futures::future;
|
|
||||||
|
|
||||||
use actix_web_httpauth::middleware::HttpAuthentication;
|
use actix_web_httpauth::middleware::HttpAuthentication;
|
||||||
|
|
||||||
fn main() -> std::io::Result<()> {
|
#[actix_rt::main]
|
||||||
|
async fn main() -> std::io::Result<()> {
|
||||||
HttpServer::new(|| {
|
HttpServer::new(|| {
|
||||||
let auth = HttpAuthentication::basic(|req, _credentials| future::ok(req));
|
let auth =
|
||||||
|
HttpAuthentication::basic(|req, _credentials| async { Ok(req) });
|
||||||
App::new()
|
App::new()
|
||||||
.wrap(middleware::Logger::default())
|
.wrap(middleware::Logger::default())
|
||||||
.wrap(auth)
|
.wrap(auth)
|
||||||
.service(web::resource("/").to(|| "Test\r\n"))
|
.service(web::resource("/").to(|| async { "Test\r\n" }))
|
||||||
})
|
})
|
||||||
.bind("127.0.0.1:8080")?
|
.bind("127.0.0.1:8080")?
|
||||||
.workers(1)
|
.workers(1)
|
||||||
.run()
|
.run()
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
@ -1,27 +1,27 @@
|
|||||||
use actix_web::dev::ServiceRequest;
|
use actix_web::dev::ServiceRequest;
|
||||||
use actix_web::{middleware, web, App, Error, HttpServer};
|
use actix_web::{middleware, web, App, Error, HttpServer};
|
||||||
|
|
||||||
use futures::future;
|
|
||||||
|
|
||||||
use actix_web_httpauth::extractors::basic::BasicAuth;
|
use actix_web_httpauth::extractors::basic::BasicAuth;
|
||||||
use actix_web_httpauth::middleware::HttpAuthentication;
|
use actix_web_httpauth::middleware::HttpAuthentication;
|
||||||
|
|
||||||
fn validator(
|
async fn validator(
|
||||||
req: ServiceRequest,
|
req: ServiceRequest,
|
||||||
_credentials: BasicAuth,
|
_credentials: BasicAuth,
|
||||||
) -> future::FutureResult<ServiceRequest, Error> {
|
) -> Result<ServiceRequest, Error> {
|
||||||
future::ok(req)
|
Ok(req)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> std::io::Result<()> {
|
#[actix_rt::main]
|
||||||
|
async fn main() -> std::io::Result<()> {
|
||||||
HttpServer::new(|| {
|
HttpServer::new(|| {
|
||||||
let auth = HttpAuthentication::basic(validator);
|
let auth = HttpAuthentication::basic(validator);
|
||||||
App::new()
|
App::new()
|
||||||
.wrap(middleware::Logger::default())
|
.wrap(middleware::Logger::default())
|
||||||
.wrap(auth)
|
.wrap(auth)
|
||||||
.service(web::resource("/").to(|| "Test\r\n"))
|
.service(web::resource("/").to(|| async { "Test\r\n" }))
|
||||||
})
|
})
|
||||||
.bind("127.0.0.1:8080")?
|
.bind("127.0.0.1:8080")?
|
||||||
.workers(1)
|
.workers(1)
|
||||||
.run()
|
.run()
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
@ -5,6 +5,7 @@ use std::borrow::Cow;
|
|||||||
use actix_web::dev::{Payload, ServiceRequest};
|
use actix_web::dev::{Payload, ServiceRequest};
|
||||||
use actix_web::http::header::Header;
|
use actix_web::http::header::Header;
|
||||||
use actix_web::{FromRequest, HttpRequest};
|
use actix_web::{FromRequest, HttpRequest};
|
||||||
|
use futures::future;
|
||||||
|
|
||||||
use super::config::AuthExtractorConfig;
|
use super::config::AuthExtractorConfig;
|
||||||
use super::errors::AuthenticationError;
|
use super::errors::AuthenticationError;
|
||||||
@ -57,7 +58,7 @@ impl AuthExtractorConfig for Config {
|
|||||||
/// use actix_web::Result;
|
/// use actix_web::Result;
|
||||||
/// use actix_web_httpauth::extractors::basic::BasicAuth;
|
/// use actix_web_httpauth::extractors::basic::BasicAuth;
|
||||||
///
|
///
|
||||||
/// fn index(auth: BasicAuth) -> String {
|
/// async fn index(auth: BasicAuth) -> String {
|
||||||
/// format!("Hello, {}!", auth.user_id())
|
/// format!("Hello, {}!", auth.user_id())
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
@ -72,7 +73,7 @@ impl AuthExtractorConfig for Config {
|
|||||||
/// use actix_web::{web, App};
|
/// use actix_web::{web, App};
|
||||||
/// use actix_web_httpauth::extractors::basic::{BasicAuth, Config};
|
/// use actix_web_httpauth::extractors::basic::{BasicAuth, Config};
|
||||||
///
|
///
|
||||||
/// fn index(auth: BasicAuth) -> String {
|
/// async fn index(auth: BasicAuth) -> String {
|
||||||
/// format!("Hello, {}!", auth.user_id())
|
/// format!("Hello, {}!", auth.user_id())
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
@ -101,7 +102,7 @@ impl BasicAuth {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl FromRequest for BasicAuth {
|
impl FromRequest for BasicAuth {
|
||||||
type Future = Result<Self, Self::Error>;
|
type Future = future::Ready<Result<Self, Self::Error>>;
|
||||||
type Config = Config;
|
type Config = Config;
|
||||||
type Error = AuthenticationError<Challenge>;
|
type Error = AuthenticationError<Challenge>;
|
||||||
|
|
||||||
@ -109,6 +110,7 @@ impl FromRequest for BasicAuth {
|
|||||||
req: &HttpRequest,
|
req: &HttpRequest,
|
||||||
_: &mut Payload,
|
_: &mut Payload,
|
||||||
) -> <Self as FromRequest>::Future {
|
) -> <Self as FromRequest>::Future {
|
||||||
|
future::ready(
|
||||||
Authorization::<Basic>::parse(req)
|
Authorization::<Basic>::parse(req)
|
||||||
.map(|auth| BasicAuth(auth.into_scheme()))
|
.map(|auth| BasicAuth(auth.into_scheme()))
|
||||||
.map_err(|_| {
|
.map_err(|_| {
|
||||||
@ -120,15 +122,17 @@ impl FromRequest for BasicAuth {
|
|||||||
.unwrap_or_else(Default::default);
|
.unwrap_or_else(Default::default);
|
||||||
|
|
||||||
AuthenticationError::new(challenge)
|
AuthenticationError::new(challenge)
|
||||||
})
|
}),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AuthExtractor for BasicAuth {
|
impl AuthExtractor for BasicAuth {
|
||||||
type Error = AuthenticationError<Challenge>;
|
type Error = AuthenticationError<Challenge>;
|
||||||
type Future = Result<Self, Self::Error>;
|
type Future = future::Ready<Result<Self, Self::Error>>;
|
||||||
|
|
||||||
fn from_service_request(req: &ServiceRequest) -> Self::Future {
|
fn from_service_request(req: &ServiceRequest) -> Self::Future {
|
||||||
|
future::ready(
|
||||||
Authorization::<Basic>::parse(req)
|
Authorization::<Basic>::parse(req)
|
||||||
.map(|auth| BasicAuth(auth.into_scheme()))
|
.map(|auth| BasicAuth(auth.into_scheme()))
|
||||||
.map_err(|_| {
|
.map_err(|_| {
|
||||||
@ -140,6 +144,7 @@ impl AuthExtractor for BasicAuth {
|
|||||||
.unwrap_or_else(Default::default);
|
.unwrap_or_else(Default::default);
|
||||||
|
|
||||||
AuthenticationError::new(challenge)
|
AuthenticationError::new(challenge)
|
||||||
})
|
}),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,6 +6,7 @@ use std::default::Default;
|
|||||||
use actix_web::dev::{Payload, ServiceRequest};
|
use actix_web::dev::{Payload, ServiceRequest};
|
||||||
use actix_web::http::header::Header;
|
use actix_web::http::header::Header;
|
||||||
use actix_web::{FromRequest, HttpRequest};
|
use actix_web::{FromRequest, HttpRequest};
|
||||||
|
use futures::future;
|
||||||
|
|
||||||
use super::config::AuthExtractorConfig;
|
use super::config::AuthExtractorConfig;
|
||||||
use super::errors::AuthenticationError;
|
use super::errors::AuthenticationError;
|
||||||
@ -60,7 +61,7 @@ impl AuthExtractorConfig for Config {
|
|||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_web_httpauth::extractors::bearer::BearerAuth;
|
/// use actix_web_httpauth::extractors::bearer::BearerAuth;
|
||||||
///
|
///
|
||||||
/// fn index(auth: BearerAuth) -> String {
|
/// async fn index(auth: BearerAuth) -> String {
|
||||||
/// format!("Hello, user with token {}!", auth.token())
|
/// format!("Hello, user with token {}!", auth.token())
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
@ -75,7 +76,7 @@ impl AuthExtractorConfig for Config {
|
|||||||
/// use actix_web::{web, App};
|
/// use actix_web::{web, App};
|
||||||
/// use actix_web_httpauth::extractors::bearer::{BearerAuth, Config};
|
/// use actix_web_httpauth::extractors::bearer::{BearerAuth, Config};
|
||||||
///
|
///
|
||||||
/// fn index(auth: BearerAuth) -> String {
|
/// async fn index(auth: BearerAuth) -> String {
|
||||||
/// format!("Hello, {}!", auth.token())
|
/// format!("Hello, {}!", auth.token())
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
@ -101,13 +102,14 @@ impl BearerAuth {
|
|||||||
|
|
||||||
impl FromRequest for BearerAuth {
|
impl FromRequest for BearerAuth {
|
||||||
type Config = Config;
|
type Config = Config;
|
||||||
type Future = Result<Self, Self::Error>;
|
type Future = future::Ready<Result<Self, Self::Error>>;
|
||||||
type Error = AuthenticationError<bearer::Bearer>;
|
type Error = AuthenticationError<bearer::Bearer>;
|
||||||
|
|
||||||
fn from_request(
|
fn from_request(
|
||||||
req: &HttpRequest,
|
req: &HttpRequest,
|
||||||
_payload: &mut Payload,
|
_payload: &mut Payload,
|
||||||
) -> <Self as FromRequest>::Future {
|
) -> <Self as FromRequest>::Future {
|
||||||
|
future::ready(
|
||||||
authorization::Authorization::<authorization::Bearer>::parse(req)
|
authorization::Authorization::<authorization::Bearer>::parse(req)
|
||||||
.map(|auth| BearerAuth(auth.into_scheme()))
|
.map(|auth| BearerAuth(auth.into_scheme()))
|
||||||
.map_err(|_| {
|
.map_err(|_| {
|
||||||
@ -117,15 +119,17 @@ impl FromRequest for BearerAuth {
|
|||||||
.unwrap_or_else(Default::default);
|
.unwrap_or_else(Default::default);
|
||||||
|
|
||||||
AuthenticationError::new(bearer)
|
AuthenticationError::new(bearer)
|
||||||
})
|
}),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AuthExtractor for BearerAuth {
|
impl AuthExtractor for BearerAuth {
|
||||||
type Future = Result<Self, Self::Error>;
|
type Future = future::Ready<Result<Self, Self::Error>>;
|
||||||
type Error = AuthenticationError<bearer::Bearer>;
|
type Error = AuthenticationError<bearer::Bearer>;
|
||||||
|
|
||||||
fn from_service_request(req: &ServiceRequest) -> Self::Future {
|
fn from_service_request(req: &ServiceRequest) -> Self::Future {
|
||||||
|
future::ready(
|
||||||
authorization::Authorization::<authorization::Bearer>::parse(req)
|
authorization::Authorization::<authorization::Bearer>::parse(req)
|
||||||
.map(|auth| BearerAuth(auth.into_scheme()))
|
.map(|auth| BearerAuth(auth.into_scheme()))
|
||||||
.map_err(|_| {
|
.map_err(|_| {
|
||||||
@ -135,7 +139,8 @@ impl AuthExtractor for BearerAuth {
|
|||||||
.unwrap_or_else(Default::default);
|
.unwrap_or_else(Default::default);
|
||||||
|
|
||||||
AuthenticationError::new(bearer)
|
AuthenticationError::new(bearer)
|
||||||
})
|
}),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
use actix_web::dev::ServiceRequest;
|
use actix_web::dev::ServiceRequest;
|
||||||
use actix_web::Error;
|
use actix_web::Error;
|
||||||
use futures::IntoFuture;
|
use futures::future::Future;
|
||||||
|
|
||||||
pub mod basic;
|
pub mod basic;
|
||||||
pub mod bearer;
|
pub mod bearer;
|
||||||
@ -26,7 +26,7 @@ pub trait AuthExtractor: Sized {
|
|||||||
type Error: Into<Error>;
|
type Error: Into<Error>;
|
||||||
|
|
||||||
/// Future that resolves into extracted credentials type.
|
/// Future that resolves into extracted credentials type.
|
||||||
type Future: IntoFuture<Item = Self, Error = Self::Error>;
|
type Future: Future<Output = Result<Self, Self::Error>>;
|
||||||
|
|
||||||
/// Parse the authentication credentials from the actix' `ServiceRequest`.
|
/// Parse the authentication credentials from the actix' `ServiceRequest`.
|
||||||
fn from_service_request(req: &ServiceRequest) -> Self::Future;
|
fn from_service_request(req: &ServiceRequest) -> Self::Future;
|
||||||
|
@ -3,7 +3,7 @@ use std::fmt;
|
|||||||
use std::str;
|
use std::str;
|
||||||
|
|
||||||
use actix_web::http::header::{
|
use actix_web::http::header::{
|
||||||
HeaderValue, IntoHeaderValue, InvalidHeaderValueBytes,
|
HeaderValue, IntoHeaderValue, InvalidHeaderValue,
|
||||||
};
|
};
|
||||||
use base64;
|
use base64;
|
||||||
use bytes::{BufMut, BytesMut};
|
use bytes::{BufMut, BytesMut};
|
||||||
@ -101,7 +101,7 @@ impl fmt::Display for Basic {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl IntoHeaderValue for Basic {
|
impl IntoHeaderValue for Basic {
|
||||||
type Error = InvalidHeaderValueBytes;
|
type Error = InvalidHeaderValue;
|
||||||
|
|
||||||
fn try_into(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
|
fn try_into(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
|
||||||
let mut credentials = BytesMut::with_capacity(
|
let mut credentials = BytesMut::with_capacity(
|
||||||
@ -123,7 +123,7 @@ impl IntoHeaderValue for Basic {
|
|||||||
value.put("Basic ");
|
value.put("Basic ");
|
||||||
value.put(&encoded);
|
value.put(&encoded);
|
||||||
|
|
||||||
HeaderValue::from_shared(value.freeze())
|
HeaderValue::from_maybe_shared(value.freeze())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2,7 +2,7 @@ use std::borrow::Cow;
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
use actix_web::http::header::{
|
use actix_web::http::header::{
|
||||||
HeaderValue, IntoHeaderValue, InvalidHeaderValueBytes,
|
HeaderValue, IntoHeaderValue, InvalidHeaderValue,
|
||||||
};
|
};
|
||||||
use bytes::{BufMut, BytesMut};
|
use bytes::{BufMut, BytesMut};
|
||||||
|
|
||||||
@ -76,14 +76,14 @@ impl fmt::Display for Bearer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl IntoHeaderValue for Bearer {
|
impl IntoHeaderValue for Bearer {
|
||||||
type Error = InvalidHeaderValueBytes;
|
type Error = InvalidHeaderValue;
|
||||||
|
|
||||||
fn try_into(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
|
fn try_into(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
|
||||||
let mut buffer = BytesMut::with_capacity(7 + self.token.len());
|
let mut buffer = BytesMut::with_capacity(7 + self.token.len());
|
||||||
buffer.put("Bearer ");
|
buffer.put("Bearer ");
|
||||||
buffer.extend_from_slice(self.token.as_bytes());
|
buffer.extend_from_slice(self.token.as_bytes());
|
||||||
|
|
||||||
HeaderValue::from_shared(buffer.freeze())
|
HeaderValue::from_maybe_shared(buffer.freeze())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -6,7 +6,7 @@ use std::fmt;
|
|||||||
use std::str;
|
use std::str;
|
||||||
|
|
||||||
use actix_web::http::header::{
|
use actix_web::http::header::{
|
||||||
HeaderValue, IntoHeaderValue, InvalidHeaderValueBytes,
|
HeaderValue, IntoHeaderValue, InvalidHeaderValue,
|
||||||
};
|
};
|
||||||
use bytes::{BufMut, Bytes, BytesMut};
|
use bytes::{BufMut, Bytes, BytesMut};
|
||||||
|
|
||||||
@ -106,10 +106,10 @@ impl fmt::Display for Basic {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl IntoHeaderValue for Basic {
|
impl IntoHeaderValue for Basic {
|
||||||
type Error = InvalidHeaderValueBytes;
|
type Error = InvalidHeaderValue;
|
||||||
|
|
||||||
fn try_into(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
|
fn try_into(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
|
||||||
HeaderValue::from_shared(self.to_bytes())
|
HeaderValue::from_maybe_shared(self.to_bytes())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,7 +3,7 @@ use std::fmt;
|
|||||||
use std::str;
|
use std::str;
|
||||||
|
|
||||||
use actix_web::http::header::{
|
use actix_web::http::header::{
|
||||||
HeaderValue, IntoHeaderValue, InvalidHeaderValueBytes,
|
HeaderValue, IntoHeaderValue, InvalidHeaderValue,
|
||||||
};
|
};
|
||||||
use bytes::{BufMut, Bytes, BytesMut};
|
use bytes::{BufMut, Bytes, BytesMut};
|
||||||
|
|
||||||
@ -133,9 +133,9 @@ impl fmt::Display for Bearer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl IntoHeaderValue for Bearer {
|
impl IntoHeaderValue for Bearer {
|
||||||
type Error = InvalidHeaderValueBytes;
|
type Error = InvalidHeaderValue;
|
||||||
|
|
||||||
fn try_into(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
|
fn try_into(self) -> Result<HeaderValue, <Self as IntoHeaderValue>::Error> {
|
||||||
HeaderValue::from_shared(self.to_bytes())
|
HeaderValue::from_maybe_shared(self.to_bytes())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,14 +1,15 @@
|
|||||||
//! HTTP Authentication middleware.
|
//! HTTP Authentication middleware.
|
||||||
|
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
use std::pin::Pin;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use actix_service::{Service, Transform};
|
use actix_service::{Service, Transform};
|
||||||
use actix_web::dev::{ServiceRequest, ServiceResponse};
|
use actix_web::dev::{ServiceRequest, ServiceResponse};
|
||||||
use actix_web::Error;
|
use actix_web::Error;
|
||||||
use futures::future::{self, FutureResult};
|
use futures::future::{self, Future, FutureExt, LocalBoxFuture, TryFutureExt};
|
||||||
use futures::{Async, Future, IntoFuture, Poll};
|
use futures::lock::Mutex;
|
||||||
use futures_locks::Mutex;
|
use futures::task::{Context, Poll};
|
||||||
|
|
||||||
use crate::extractors::{basic, bearer, AuthExtractor};
|
use crate::extractors::{basic, bearer, AuthExtractor};
|
||||||
|
|
||||||
@ -35,7 +36,7 @@ impl<T, F, O> HttpAuthentication<T, F>
|
|||||||
where
|
where
|
||||||
T: AuthExtractor,
|
T: AuthExtractor,
|
||||||
F: Fn(ServiceRequest, T) -> O,
|
F: Fn(ServiceRequest, T) -> O,
|
||||||
O: IntoFuture<Item = ServiceRequest, Error = Error>,
|
O: Future<Output = Result<ServiceRequest, Error>>,
|
||||||
{
|
{
|
||||||
/// Construct `HttpAuthentication` middleware
|
/// Construct `HttpAuthentication` middleware
|
||||||
/// with the provided auth extractor `T` and
|
/// with the provided auth extractor `T` and
|
||||||
@ -51,7 +52,7 @@ where
|
|||||||
impl<F, O> HttpAuthentication<basic::BasicAuth, F>
|
impl<F, O> HttpAuthentication<basic::BasicAuth, F>
|
||||||
where
|
where
|
||||||
F: Fn(ServiceRequest, basic::BasicAuth) -> O,
|
F: Fn(ServiceRequest, basic::BasicAuth) -> O,
|
||||||
O: IntoFuture<Item = ServiceRequest, Error = Error>,
|
O: Future<Output = Result<ServiceRequest, Error>>,
|
||||||
{
|
{
|
||||||
/// Construct `HttpAuthentication` middleware for the HTTP "Basic"
|
/// Construct `HttpAuthentication` middleware for the HTTP "Basic"
|
||||||
/// authentication scheme.
|
/// authentication scheme.
|
||||||
@ -61,7 +62,6 @@ where
|
|||||||
/// ```rust
|
/// ```rust
|
||||||
/// # use actix_web::Error;
|
/// # use actix_web::Error;
|
||||||
/// # use actix_web::dev::ServiceRequest;
|
/// # use actix_web::dev::ServiceRequest;
|
||||||
/// # use futures::future::{self, FutureResult};
|
|
||||||
/// # use actix_web_httpauth::middleware::HttpAuthentication;
|
/// # use actix_web_httpauth::middleware::HttpAuthentication;
|
||||||
/// # use actix_web_httpauth::extractors::basic::BasicAuth;
|
/// # use actix_web_httpauth::extractors::basic::BasicAuth;
|
||||||
/// // In this example validator returns immediately,
|
/// // In this example validator returns immediately,
|
||||||
@ -69,12 +69,12 @@ where
|
|||||||
/// // that implements `IntoFuture` trait,
|
/// // that implements `IntoFuture` trait,
|
||||||
/// // it can be extended to query database
|
/// // it can be extended to query database
|
||||||
/// // or to do something else in a async manner.
|
/// // or to do something else in a async manner.
|
||||||
/// fn validator(
|
/// async fn validator(
|
||||||
/// req: ServiceRequest,
|
/// req: ServiceRequest,
|
||||||
/// credentials: BasicAuth,
|
/// credentials: BasicAuth,
|
||||||
/// ) -> FutureResult<ServiceRequest, Error> {
|
/// ) -> Result<ServiceRequest, Error> {
|
||||||
/// // All users are great and more than welcome!
|
/// // All users are great and more than welcome!
|
||||||
/// future::ok(req)
|
/// Ok(req)
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
/// let middleware = HttpAuthentication::basic(validator);
|
/// let middleware = HttpAuthentication::basic(validator);
|
||||||
@ -87,7 +87,7 @@ where
|
|||||||
impl<F, O> HttpAuthentication<bearer::BearerAuth, F>
|
impl<F, O> HttpAuthentication<bearer::BearerAuth, F>
|
||||||
where
|
where
|
||||||
F: Fn(ServiceRequest, bearer::BearerAuth) -> O,
|
F: Fn(ServiceRequest, bearer::BearerAuth) -> O,
|
||||||
O: IntoFuture<Item = ServiceRequest, Error = Error>,
|
O: Future<Output = Result<ServiceRequest, Error>>,
|
||||||
{
|
{
|
||||||
/// Construct `HttpAuthentication` middleware for the HTTP "Bearer"
|
/// Construct `HttpAuthentication` middleware for the HTTP "Bearer"
|
||||||
/// authentication scheme.
|
/// authentication scheme.
|
||||||
@ -97,20 +97,19 @@ where
|
|||||||
/// ```rust
|
/// ```rust
|
||||||
/// # use actix_web::Error;
|
/// # use actix_web::Error;
|
||||||
/// # use actix_web::dev::ServiceRequest;
|
/// # use actix_web::dev::ServiceRequest;
|
||||||
/// # use futures::future::{self, FutureResult};
|
|
||||||
/// # use actix_web_httpauth::middleware::HttpAuthentication;
|
/// # use actix_web_httpauth::middleware::HttpAuthentication;
|
||||||
/// # use actix_web_httpauth::extractors::bearer::{Config, BearerAuth};
|
/// # use actix_web_httpauth::extractors::bearer::{Config, BearerAuth};
|
||||||
/// # use actix_web_httpauth::extractors::{AuthenticationError, AuthExtractorConfig};
|
/// # use actix_web_httpauth::extractors::{AuthenticationError, AuthExtractorConfig};
|
||||||
/// fn validator(req: ServiceRequest, credentials: BearerAuth) -> FutureResult<ServiceRequest, Error> {
|
/// async fn validator(req: ServiceRequest, credentials: BearerAuth) -> Result<ServiceRequest, Error> {
|
||||||
/// if credentials.token() == "mF_9.B5f-4.1JqM" {
|
/// if credentials.token() == "mF_9.B5f-4.1JqM" {
|
||||||
/// future::ok(req)
|
/// Ok(req)
|
||||||
/// } else {
|
/// } else {
|
||||||
/// let config = req.app_data::<Config>()
|
/// let config = req.app_data::<Config>()
|
||||||
/// .map(|data| data.get_ref().clone())
|
/// .map(|data| data.get_ref().clone())
|
||||||
/// .unwrap_or_else(Default::default)
|
/// .unwrap_or_else(Default::default)
|
||||||
/// .scope("urn:example:channel=HBO&urn:example:rating=G,PG-13");
|
/// .scope("urn:example:channel=HBO&urn:example:rating=G,PG-13");
|
||||||
///
|
///
|
||||||
/// future::err(AuthenticationError::from(config).into())
|
/// Err(AuthenticationError::from(config).into())
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
@ -130,7 +129,7 @@ where
|
|||||||
> + 'static,
|
> + 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
F: Fn(ServiceRequest, T) -> O + 'static,
|
F: Fn(ServiceRequest, T) -> O + 'static,
|
||||||
O: IntoFuture<Item = ServiceRequest, Error = Error> + 'static,
|
O: Future<Output = Result<ServiceRequest, Error>> + 'static,
|
||||||
T: AuthExtractor + 'static,
|
T: AuthExtractor + 'static,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
@ -138,11 +137,11 @@ where
|
|||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Transform = AuthenticationMiddleware<S, F, T>;
|
type Transform = AuthenticationMiddleware<S, F, T>;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
type Future = future::Ready<Result<Self::Transform, Self::InitError>>;
|
||||||
|
|
||||||
fn new_transform(&self, service: S) -> Self::Future {
|
fn new_transform(&self, service: S) -> Self::Future {
|
||||||
future::ok(AuthenticationMiddleware {
|
future::ok(AuthenticationMiddleware {
|
||||||
service: Mutex::new(service),
|
service: Arc::new(Mutex::new(service)),
|
||||||
process_fn: self.process_fn.clone(),
|
process_fn: self.process_fn.clone(),
|
||||||
_extractor: PhantomData,
|
_extractor: PhantomData,
|
||||||
})
|
})
|
||||||
@ -154,7 +153,7 @@ pub struct AuthenticationMiddleware<S, F, T>
|
|||||||
where
|
where
|
||||||
T: AuthExtractor,
|
T: AuthExtractor,
|
||||||
{
|
{
|
||||||
service: Mutex<S>,
|
service: Arc<Mutex<S>>,
|
||||||
process_fn: Arc<F>,
|
process_fn: Arc<F>,
|
||||||
_extractor: PhantomData<T>,
|
_extractor: PhantomData<T>,
|
||||||
}
|
}
|
||||||
@ -168,19 +167,22 @@ where
|
|||||||
> + 'static,
|
> + 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
F: Fn(ServiceRequest, T) -> O + 'static,
|
F: Fn(ServiceRequest, T) -> O + 'static,
|
||||||
O: IntoFuture<Item = ServiceRequest, Error = Error> + 'static,
|
O: Future<Output = Result<ServiceRequest, Error>> + 'static,
|
||||||
T: AuthExtractor + 'static,
|
T: AuthExtractor + 'static,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = S::Error;
|
type Error = S::Error;
|
||||||
type Future = Box<dyn Future<Item = ServiceResponse<B>, Error = Error>>;
|
type Future = LocalBoxFuture<'static, Result<ServiceResponse<B>, Error>>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut Context<'_>,
|
||||||
|
) -> Poll<Result<(), Self::Error>> {
|
||||||
self.service
|
self.service
|
||||||
.try_lock()
|
.try_lock()
|
||||||
.expect("AuthenticationMiddleware was called already")
|
.expect("AuthenticationMiddleware was called already")
|
||||||
.poll_ready()
|
.poll_ready(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||||
@ -188,23 +190,20 @@ where
|
|||||||
// Note: cloning the mutex, not the service itself
|
// Note: cloning the mutex, not the service itself
|
||||||
let inner = self.service.clone();
|
let inner = self.service.clone();
|
||||||
|
|
||||||
let f = Extract::new(req)
|
async move {
|
||||||
.and_then(move |(req, credentials)| (process_fn)(req, credentials))
|
let (req, credentials) = Extract::<T>::new(req).await?;
|
||||||
.and_then(move |req| {
|
let req = process_fn(req, credentials).await?;
|
||||||
inner
|
let mut service = inner.lock().await;
|
||||||
.lock()
|
service.call(req).await
|
||||||
.map_err(Into::into)
|
}
|
||||||
.and_then(|mut service| service.call(req))
|
.boxed_local()
|
||||||
});
|
|
||||||
|
|
||||||
Box::new(f)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Extract<T> {
|
struct Extract<T> {
|
||||||
req: Option<ServiceRequest>,
|
req: Option<ServiceRequest>,
|
||||||
f: Option<Box<dyn Future<Item = T, Error = Error>>>,
|
f: Option<LocalBoxFuture<'static, Result<T, Error>>>,
|
||||||
_extractor: PhantomData<T>,
|
_extractor: PhantomData<fn() -> T>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Extract<T> {
|
impl<T> Extract<T> {
|
||||||
@ -223,26 +222,26 @@ where
|
|||||||
T::Future: 'static,
|
T::Future: 'static,
|
||||||
T::Error: 'static,
|
T::Error: 'static,
|
||||||
{
|
{
|
||||||
type Item = (ServiceRequest, T);
|
type Output = Result<(ServiceRequest, T), Error>;
|
||||||
type Error = Error;
|
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
ctx: &mut Context<'_>,
|
||||||
|
) -> Poll<Self::Output> {
|
||||||
if self.f.is_none() {
|
if self.f.is_none() {
|
||||||
let req =
|
let req =
|
||||||
self.req.as_ref().expect("Extract future was polled twice!");
|
self.req.as_ref().expect("Extract future was polled twice!");
|
||||||
let f = T::from_service_request(req)
|
let f = T::from_service_request(req).map_err(Into::into);
|
||||||
.into_future()
|
self.f = Some(f.boxed_local());
|
||||||
.map_err(Into::into);
|
|
||||||
self.f = Some(Box::new(f));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let f = self
|
let f = self
|
||||||
.f
|
.f
|
||||||
.as_mut()
|
.as_mut()
|
||||||
.expect("Extraction future should be initialized at this point");
|
.expect("Extraction future should be initialized at this point");
|
||||||
let credentials = futures::try_ready!(f.poll());
|
let credentials = futures::ready!(Future::poll(f.as_mut(), ctx))?;
|
||||||
|
|
||||||
let req = self.req.take().expect("Extract future was polled twice!");
|
let req = self.req.take().expect("Extract future was polled twice!");
|
||||||
Ok(Async::Ready((req, credentials)))
|
Poll::Ready(Ok((req, credentials)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user