actix-web icon indicating copy to clipboard operation
actix-web copied to clipboard

Unexpected middleware chaining behaviour - needs explanation / documentation

Open brecht-derooms opened this issue 2 years ago • 0 comments
trafficstars

Expected Behavior

The actix documentation currently mentions: "Middleware is registered for each App, scope, or Resource and executed in the opposite order as registration" When I read that phrase I would expect the following to work and call the 'bypass auth middleware' first for the authentication endpoints before the CookieAuthMiddleware

wrap(auth_middleware::middleware::CookieAuthMiddlewareFactory::new())
            .app_data(app_state.clone())
            .service(web::scope("api").configure(controller::api::conf))
            .service(
                web::scope("oauth2")
                    .wrap(auth_middleware::middleware::BypassAuthMiddlewareFactory::new())
                    .configure(auth_middleware::controller::oauth2::conf),

Current Behavior

Currently, it seems that middleware defined within a scope is not called before the 'global' middleware although I consider that later in the 'order of registration'. Maybe the registration in a scope is delayed or something else is amiss. It probably is worthwhile to complete the documentation with more advanced usages of middleware and how multiple middleware would interact with each other in different configurations.

More context

The equivalent working version of what I intended above is:

service(
                web::scope("api")
                    .wrap(auth_middleware::middleware::CookieAuthMiddlewareFactory::new())
                    .configure(controller::api::conf),
            )
            .service(
                web::scope("oauth2")
                    .wrap(auth_middleware::middleware::CookieAuthMiddlewareFactory::new())
                    .wrap(auth_middleware::middleware::BypassAuthMiddlewareFactory::new())
                    .configure(auth_middleware::controller::oauth2::conf),

However, what I really want to achieve here is to have all endpoints protected by default (secure by default) and allow people to override / bypass authentication only in certain cases since I personally have better experiences by securing everything by default and opening up things than having everything open by default and securing each endpoint or group of endpoints separately, it's easy to forget such a line with rather bad effects.

brecht-derooms avatar Mar 07 '23 13:03 brecht-derooms