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

问题描述 投票:0回答:2

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

impl Guard for AuthGuard {
    fn check(&self, ctx: &GuardContext<'_>) -> bool {
        // check header value here
        // and retrieve connection pool from app_data
    }
}
rust actix-web
2个回答
0
投票

查看GuardContext,您可以看到有

req_data
head
。因此人们可以做到。

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
或中间件。请参阅这个问题


-1
投票

的变体

让 jwt = ctx.req_data::().unwrap();

不起作用。因为 req_data 采用 0 个参数(据我所知,对于最新版本的 actix)。大概我们可以这样获取数据:

let jwt = ctx.req_data().get::().cloned().unwrap();

但我不能保证它会按照我的建议工作。

© www.soinside.com 2019 - 2024. All rights reserved.