我知道我可以使用Request guard 。然而,如果我有一个包含数百个处理程序的 REST API,那么不仅必须向所有处理程序添加额外的函数参数会很烦人,而且它有点让我害怕,因为很容易错过在此处添加这样的参数或从而造成安全漏洞。这就是为什么我想知道是否有办法在全局进行这样的验证。
关于 Fairings 的文档提到它们可以用于全局安全策略:
As a general rule of thumb, only globally applicable actions should be implemented via fairings. For instance, you should not use a fairing to implement authentication or authorization (preferring to use a request guard instead) unless the authentication or authorization applies to the entire application. On the other hand, you should use a fairing to record timing and/or usage statistics or to implement global security policies.
但同时 on_request()
回调的文档是这样说的:
A request callback can modify the request at will and Data::peek() into the incoming data. It may not, however, abort or respond directly to the request; these issues are better handled via request guards or via response callbacks.
那么,例如,在 token 无效的情况下,我应该如何向用户返回错误?
最佳答案
好吧,我想我找到了办法......
首先我们创建一个“虚拟”处理程序,如下所示:
#[put("/errHnd", format = "json")]
fn err_handler() -> ApiResult {
// Here simply return an error
}
然后我们附加一个像这样的整流罩:
rocket::custom(cfg)
.attach(AdHoc::on_request("OnReq", |req, _| {
// Here we validate the token and if it's not OK,
// forward the request to our "dummy" handler:
let u = Origin::parse("/errHnd").unwrap();
req.set_uri(u);
req.set_method(Method::Put);
}))
.mount("/", routes![err_handler, ...
我不确定这是最好的方法,但我测试了它,它似乎有效。我愿意接受其他建议。
附注还值得一提的是,如果我们想要一个异常(exception),以便跳过整流罩中的验证,例如,基于 URL,我们可以简单地在其中添加类似这样的内容:
if req.uri().path() == "/let-me-in-please" {
return;
}
关于rust - Rocket 中基于 header 的全局认证/授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70011965/