actix / actix/actix-web

Unexpected middleware chaining behaviour - needs explanation / documentation

Open
#2,993 0 comments 3 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
24.8k
Forks
1.9k
Avg merge
23h 10m
Merged PRs (30d)
26

Description

## 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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.