我正在尝试实现一个自定义防护来检查授权令牌是否有效:
impl Guard for AuthGuard {
fn check(&self, ctx: &GuardContext<'_>) -> bool {
// check header value here
// and retrieve connection pool from app_data
}
}
查看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)
}
}
你想要的东西都在那里,但请记住支票是阻塞的。
如果您需要执行异步操作,您可能需要考虑
FromRequest
或中间件。请参阅这个问题。
与
的变体让 jwt = ctx.req_data::().unwrap();
不起作用。因为 req_data 采用 0 个参数(据我所知,对于最新版本的 actix)。大概我们可以这样获取数据:
let jwt = ctx.req_data().get::().cloned().unwrap();
但我不能保证它会按照我的建议工作。