mirror of
https://github.com/TECHNOFAB11/jwt-authorizer.git
synced 2025-12-11 23:50:07 +01:00
refactor: simplification ToAuthorizationLayer -> IntoLayer
This commit is contained in:
parent
0fbdc0df84
commit
50c2ecac38
5 changed files with 20 additions and 22 deletions
|
|
@ -1,7 +1,5 @@
|
||||||
use axum::{routing::get, Router};
|
use axum::{routing::get, Router};
|
||||||
use jwt_authorizer::{
|
use jwt_authorizer::{error::InitError, AuthError, IntoLayer, JwtAuthorizer, JwtClaims, Refresh, RefreshStrategy};
|
||||||
error::InitError, AuthError, JwtAuthorizer, JwtClaims, Refresh, RefreshStrategy, ToAuthorizationLayer,
|
|
||||||
};
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use tower_http::trace::TraceLayer;
|
use tower_http::trace::TraceLayer;
|
||||||
|
|
@ -51,7 +49,7 @@ async fn main() -> Result<(), InitError> {
|
||||||
let api = Router::new()
|
let api = Router::new()
|
||||||
.route("/protected", get(protected))
|
.route("/protected", get(protected))
|
||||||
// adding the authorizer layer
|
// adding the authorizer layer
|
||||||
.layer(jwt_auth.to_layer().await?);
|
.layer(jwt_auth.into_layer().await?);
|
||||||
|
|
||||||
let app = Router::new()
|
let app = Router::new()
|
||||||
// public endpoint
|
// public endpoint
|
||||||
|
|
|
||||||
|
|
@ -195,11 +195,11 @@ where
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<C> ToAuthorizationLayer<C> for JwtAuthorizer<C>
|
impl<C> IntoLayer<C> for JwtAuthorizer<C>
|
||||||
where
|
where
|
||||||
C: Clone + DeserializeOwned + Send + Sync,
|
C: Clone + DeserializeOwned + Send + Sync,
|
||||||
{
|
{
|
||||||
async fn to_layer(self) -> Result<AsyncAuthorizationLayer<C>, InitError> {
|
async fn into_layer(self) -> Result<AsyncAuthorizationLayer<C>, InitError> {
|
||||||
let val = self.validation.unwrap_or_default();
|
let val = self.validation.unwrap_or_default();
|
||||||
let auth = Arc::new(
|
let auth = Arc::new(
|
||||||
Authorizer::build(self.key_source_type, self.claims_checker, self.refresh, val, self.jwt_source).await?,
|
Authorizer::build(self.key_source_type, self.claims_checker, self.refresh, val, self.jwt_source).await?,
|
||||||
|
|
@ -209,11 +209,11 @@ where
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<C> ToAuthorizationLayer<C> for Vec<JwtAuthorizer<C>>
|
impl<C> IntoLayer<C> for Vec<JwtAuthorizer<C>>
|
||||||
where
|
where
|
||||||
C: Clone + DeserializeOwned + Send + Sync,
|
C: Clone + DeserializeOwned + Send + Sync,
|
||||||
{
|
{
|
||||||
async fn to_layer(self) -> Result<AsyncAuthorizationLayer<C>, InitError> {
|
async fn into_layer(self) -> Result<AsyncAuthorizationLayer<C>, InitError> {
|
||||||
let mut errs = Vec::<InitError>::new();
|
let mut errs = Vec::<InitError>::new();
|
||||||
let mut auths = Vec::<Arc<Authorizer<C>>>::new();
|
let mut auths = Vec::<Arc<Authorizer<C>>>::new();
|
||||||
let mut auths_futs: FuturesUnordered<_> = self
|
let mut auths_futs: FuturesUnordered<_> = self
|
||||||
|
|
@ -330,11 +330,11 @@ where
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait ToAuthorizationLayer<C>
|
pub trait IntoLayer<C>
|
||||||
where
|
where
|
||||||
C: Clone + DeserializeOwned + Send,
|
C: Clone + DeserializeOwned + Send,
|
||||||
{
|
{
|
||||||
async fn to_layer(self) -> Result<AsyncAuthorizationLayer<C>, InitError>;
|
async fn into_layer(self) -> Result<AsyncAuthorizationLayer<C>, InitError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- AsyncAuthorizationService --------
|
// ---------- AsyncAuthorizationService --------
|
||||||
|
|
@ -485,12 +485,12 @@ where
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::{JwtAuthorizer, ToAuthorizationLayer};
|
use crate::{IntoLayer, JwtAuthorizer};
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn jwt_auth_to_layer() {
|
async fn jwt_auth_to_layer() {
|
||||||
let auth1: JwtAuthorizer = JwtAuthorizer::from_secret("aaa");
|
let auth1: JwtAuthorizer = JwtAuthorizer::from_secret("aaa");
|
||||||
let layer = auth1.to_layer().await;
|
let layer = auth1.into_layer().await;
|
||||||
assert!(layer.is_ok());
|
assert!(layer.is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -499,7 +499,7 @@ mod tests {
|
||||||
let auth1: JwtAuthorizer = JwtAuthorizer::from_secret("aaa");
|
let auth1: JwtAuthorizer = JwtAuthorizer::from_secret("aaa");
|
||||||
let auth2: JwtAuthorizer = JwtAuthorizer::from_secret("bbb");
|
let auth2: JwtAuthorizer = JwtAuthorizer::from_secret("bbb");
|
||||||
let av = vec![auth1, auth2];
|
let av = vec![auth1, auth2];
|
||||||
let layer = av.to_layer().await;
|
let layer = av.into_layer().await;
|
||||||
assert!(layer.is_ok());
|
assert!(layer.is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -508,7 +508,7 @@ mod tests {
|
||||||
let auth1: JwtAuthorizer = JwtAuthorizer::from_ec_pem("aaa");
|
let auth1: JwtAuthorizer = JwtAuthorizer::from_ec_pem("aaa");
|
||||||
let auth2: JwtAuthorizer = JwtAuthorizer::from_ed_pem("bbb");
|
let auth2: JwtAuthorizer = JwtAuthorizer::from_ed_pem("bbb");
|
||||||
let av = vec![auth1, auth2];
|
let av = vec![auth1, auth2];
|
||||||
let layer = av.to_layer().await;
|
let layer = av.into_layer().await;
|
||||||
assert!(layer.is_err());
|
assert!(layer.is_err());
|
||||||
if let Err(err) = layer {
|
if let Err(err) = layer {
|
||||||
assert_eq!(err.to_string(), "No such file or directory (os error 2)");
|
assert_eq!(err.to_string(), "No such file or directory (os error 2)");
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ use serde::de::DeserializeOwned;
|
||||||
pub use self::error::AuthError;
|
pub use self::error::AuthError;
|
||||||
pub use claims::{NumericDate, OneOrArray, RegisteredClaims};
|
pub use claims::{NumericDate, OneOrArray, RegisteredClaims};
|
||||||
pub use jwks::key_store_manager::{Refresh, RefreshStrategy};
|
pub use jwks::key_store_manager::{Refresh, RefreshStrategy};
|
||||||
pub use layer::{JwtAuthorizer, ToAuthorizationLayer};
|
pub use layer::{IntoLayer, JwtAuthorizer};
|
||||||
pub use validation::Validation;
|
pub use validation::Validation;
|
||||||
|
|
||||||
pub mod authorizer;
|
pub mod authorizer;
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ use std::{
|
||||||
use axum::{response::Response, routing::get, Json, Router};
|
use axum::{response::Response, routing::get, Json, Router};
|
||||||
use http::{header::AUTHORIZATION, Request, StatusCode};
|
use http::{header::AUTHORIZATION, Request, StatusCode};
|
||||||
use hyper::Body;
|
use hyper::Body;
|
||||||
use jwt_authorizer::{JwtAuthorizer, JwtClaims, Refresh, RefreshStrategy, ToAuthorizationLayer};
|
use jwt_authorizer::{IntoLayer, JwtAuthorizer, JwtClaims, Refresh, RefreshStrategy};
|
||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
@ -104,7 +104,7 @@ async fn app(jwt_auth: JwtAuthorizer<User>) -> Router {
|
||||||
let protected_route: Router = Router::new()
|
let protected_route: Router = Router::new()
|
||||||
.route("/protected", get(protected_handler))
|
.route("/protected", get(protected_handler))
|
||||||
.route("/protected-with-user", get(protected_with_user))
|
.route("/protected-with-user", get(protected_with_user))
|
||||||
.layer(jwt_auth.to_layer().await.unwrap());
|
.layer(jwt_auth.into_layer().await.unwrap());
|
||||||
|
|
||||||
Router::new().merge(pub_route).merge(protected_route)
|
Router::new().merge(pub_route).merge(protected_route)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ mod tests {
|
||||||
BoxError, Router,
|
BoxError, Router,
|
||||||
};
|
};
|
||||||
use http::{header, HeaderValue};
|
use http::{header, HeaderValue};
|
||||||
use jwt_authorizer::{layer::JwtSource, validation::Validation, JwtAuthorizer, JwtClaims, ToAuthorizationLayer};
|
use jwt_authorizer::{layer::JwtSource, validation::Validation, IntoLayer, JwtAuthorizer, JwtClaims};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use tower::{util::MapErrLayer, ServiceExt};
|
use tower::{util::MapErrLayer, ServiceExt};
|
||||||
|
|
||||||
|
|
@ -23,7 +23,7 @@ mod tests {
|
||||||
sub: String,
|
sub: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn app(jwt_auth: impl ToAuthorizationLayer<User>) -> Router {
|
async fn app(jwt_auth: impl IntoLayer<User>) -> Router {
|
||||||
Router::new().route("/public", get(|| async { "hello" })).route(
|
Router::new().route("/public", get(|| async { "hello" })).route(
|
||||||
"/protected",
|
"/protected",
|
||||||
get(|JwtClaims(user): JwtClaims<User>| async move { format!("hello: {}", user.sub) }).layer(
|
get(|JwtClaims(user): JwtClaims<User>| async move { format!("hello: {}", user.sub) }).layer(
|
||||||
|
|
@ -32,14 +32,14 @@ mod tests {
|
||||||
tower::buffer::BufferLayer::new(1),
|
tower::buffer::BufferLayer::new(1),
|
||||||
MapErrLayer::new(|e: BoxError| -> Infallible { panic!("{}", e) }),
|
MapErrLayer::new(|e: BoxError| -> Infallible { panic!("{}", e) }),
|
||||||
),
|
),
|
||||||
jwt_auth.to_layer().await.unwrap(),
|
jwt_auth.into_layer().await.unwrap(),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn proteced_request_with_header(
|
async fn proteced_request_with_header(
|
||||||
jwt_auth: impl ToAuthorizationLayer<User>,
|
jwt_auth: impl IntoLayer<User>,
|
||||||
header_name: &str,
|
header_name: &str,
|
||||||
header_value: &str,
|
header_value: &str,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
|
|
@ -56,7 +56,7 @@ mod tests {
|
||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn make_proteced_request(jwt_auth: impl ToAuthorizationLayer<User>, bearer: &str) -> Response {
|
async fn make_proteced_request(jwt_auth: impl IntoLayer<User>, bearer: &str) -> Response {
|
||||||
proteced_request_with_header(jwt_auth, "Authorization", &format!("Bearer {bearer}")).await
|
proteced_request_with_header(jwt_auth, "Authorization", &format!("Bearer {bearer}")).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue