有没有在Actix路由级别实施验证/授权检查的好方法?

时间:2018-07-18 18:03:16

标签: authentication routing rust rust-actix

我的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);
        })
)

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

1 个答案:

答案 0 :(得分:2)

您要寻找的是middleware

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

// 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);
        })
);