Multiple auth middlewares for one handler #1549
-
Hi, I am trying to migrate from Rocket to Axum but I am stuck on porting a handler that can be accessed either via sending a bearer token (you have to be logged in and have sufficient permissions) or basic auth (secret link and an album password). There are two main ways to do such thing with Rocket: ranks (docs)#[get("/album")]
fn album(auth: BearerAuth) { /* ... */ }
#[get("/album", rank = 2)]
fn album_special(auth: BasicAuth)) { /* ... */ } If the first function fails, it automatically goes to the second one. optional request guards (optional extractors)#[get("/album")]
fn album(bearer_auth: Option<BearerAuth>, basic_auth: Option<BasicAuth>) {
if bearer_auth.is_none() && basic_auth.is_none() {
return Err(Status::NotFound);
}
/* ... */
} This way, the extractor doesn't terminate the request early when it fails and instead returns an Option. I think I could write something similar with Axum but sadly, I don't think there is a way to use State (database pool) from extractors so I am using a middleware instead. I had an idea that layers could implement logic gates let app = Router::new()
.typed_get(album)
.route_layer(middleware::from_fn_with_state(pool.clone(), bearer_auth).or(middleware::from_fn_with_state(pool, basic_auth))); but maybe allowing multiple handlers to have the same route would be better? Is there a nice way to achieve something similar with Axum? Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
There is. If you wanna use a middleware you'll have to write one middleware to handle both auth schemes. There is no such thing as |
Beta Was this translation helpful? Give feedback.
There is.
FromRequestParts
andFromRequest
both haveS
type parameter. That is the state. So you can implementFromRequestParts<YourExactState
or possibly like this https://docs.rs/axum/0.6.0-rc.5/axum/extract/struct.State.html#for-library-authors if you wanna be extra flexible.If you wanna use a middleware you'll have to write one middleware to handle both auth schemes. There is no such thing as
or
for middleware.