如何访问actix_web的 Guard::check() 函数中的app_data?



我正在尝试实现一个检查授权令牌是否有效的自定义保护:

impl Guard for AuthGuard {
fn check(&self, ctx: &GuardContext<'_>) -> bool {
// check header value here
// and retrieve connection pool from app_data
}
}

查看GuardContext,可以看到有req_datahead。因此可以这样做。

impl Guard for AuthGuard {
fn check(&self, ctx: &GuardContext<'_>) -> bool {
let jwt = ctx.req_data::<Jwt>().unwrap();
let token = ctx.head().headers().get(header::AUTHORIZATION).unwrap();
jwt.is_valid(token)
}
}

你想要的东西在那里,但记住支票是阻塞的。

  • 检查可以很好地检查令牌是否存在及其有效性。
  • 检查不适用于需要检查令牌是否存在于Redis或sqlx池的场景。

如果你需要做异步的东西,你可能需要考虑FromRequest或中间件。请看这个问题

最新更新