I'm validating my bearer token in a function that is called in a validator function.
pub fn validate_token(token: &str) -> Result<bool, HttpResponse> {
let val: Validation = Validation::new(Algorithm::HS256);
let env: String = std::env::var("PUB_KEY")
.expect("PUB_KEY must be set.");
let pub_key: &[u8] = env.as_bytes();
let unauth: &str = "The access token provided is expired, revoked, malformed, or invalid";
let bad_req: &str = "The request has a invalid or missing parameter";
let bad_gate: &str = "The request can't be handled";
match decode::<Claims>(&token, &DecodingKey::from_ec_pem(pub_key).unwrap(), &val) {
Ok(_c) => Ok(true),
Err(err) => match *err.kind() {
ErrorKind::InvalidToken => Err(HttpResponse::Unauthorized().body(unauth)),
ErrorKind::InvalidIssuer => Err(HttpResponse::BadRequest().body(bad_req)),
_ => Err(HttpResponse::BadGateway().body(bad_gate)),
},
}
}
async fn validator(
req: ServiceRequest,
credentials: BearerAuth,
) -> Result<ServiceRequest, (Error, ServiceRequest)> {
let config: bearer::Config = req.app_data::<bearer::Config>()
.cloned()
.unwrap_or_default()
.scope("urn:example:channel=HBO&urn:example:rating=G,PG-13");
match auth_service::validate_token(credentials.token()) {
Ok(res) => {
if res == true {
Ok(req)
} else {
Err((AuthenticationError::from(config).into(), req))
}
},
Err(_) => Err((AuthenticationError::from(config).into(), req))
}
}
I want to pass the claims to my endpoints but I don't know how. As far as I know app_data()
can be used to pass the claims to the endpoints but how can I access them without returning them in validate_token
and validator
?