Passing JWT claims to actix endpoint

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?

You can add the claims to the Extensions of your ServiceRequest using ServiceRequest::extensions_mut. In your route you can extract the claims with the ReqData extractor.

As to the design of your functions, I'd just return the claims from validate_token in the Ok branch instead of bool and add it to the ServiceRequest in validator. Or you can pass a reference to req to validate_token and add the claims there, though I highly prefer the first variant.

1 Like

ServiceRequest::extensions_mut is the function I was looking for, thanks!

1 Like