-2

I am trying to implement a custom guard that checks if the authorization token is valid:

impl Guard for AuthGuard {
    fn check(&self, ctx: &GuardContext<'_>) -> bool {
        // check header value here
        // and retrieve connection pool from app_data
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ferd tomale
  • 845
  • 7
  • 20

1 Answers1

0

Taking a look at GuardContext, you can see that there is req_data and head. And hence one can do.

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)
    }
}

The things you are asking for are there but remember that Checks are blocking.

  • Checks can be good to check whether a token exists and its valid.
  • Checks are not suitable in a scenario where you need to check if a token exists in Redis or sqlx pool.

If you need to do async stuff you might need to think of FromRequest or middleware. See this question.

Njuguna Mureithi
  • 3,506
  • 1
  • 21
  • 41