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

Is there a good way to implement an authentication / authorization check at the Actix route level?

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

我正在考虑添加路由级别的保护,它可以通过或 return 一个 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);
        })
)

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

您要找的是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);
        })
);