我正在尝试实现一个检查授权令牌是否有效的自定义保护:
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)
}
}
你想要的东西在那里,但记住支票是阻塞的。
- 检查可以很好地检查令牌是否存在及其有效性。
- 检查不适用于需要检查令牌是否存在于Redis或sqlx池的场景。
如果你需要做异步的东西,你可能需要考虑FromRequest
或中间件。请看这个问题