3

我的 API 路由被收集到一个范围内,如下所示:

.scope("/api", |s| s
        .nested("/doorlock", routes::doorlock)
        .resource("/config{path:.*}", |r| {
            r.get().with(routes::config::read);
            r.put().with(routes::config::write);
            r.delete().with(routes::config::delete);
        })
)

我正在考虑添加路由级保护,它可以通过或返回401 Unauthorizated如下响应:

.scope("/api", |s| s
        .filter(is_authenticated_and_authorized)
        .nested("/doorlock", routes::doorlock)
        .resource("/config{path:.*}", |r| {
            r.get().with(routes::config::read);
            r.put().with(routes::config::write);
            r.delete().with(routes::config::delete);
        })
)

不幸的是,这会将请求转发到默认处理程序,而不是在不匹配的情况下返回错误响应。

4

1 回答 1

2

您正在寻找的是中间件

然后,您可以将中间件添加到范围:

// Create middleware
struct AuthMiddleware;

impl Middleware<AppState> for AuthMiddleware {
    fn start(&self, req: &mut HttpRequest<AppState>) -> Result<Started> {
        unimplemented!() // implement your auth logic here
    }
}

// later:

App::with_state(my_state)
    .scope("/api", |s| s
        .middleware(AuthMiddleware) // add your middleware to the scope
        .nested("/doorlock", routes::doorlock)
        .resource("/config{path:.*}", |r| {
            r.get().with(routes::config::read);
            r.put().with(routes::config::write);
            r.delete().with(routes::config::delete);
        })
);
于 2018-07-18T23:25:12.933 回答