rust 如何在axum中通过from_fn函数向中间件传递可选参数?

6jygbczu  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(261)

在我的axum后端,我希望能够确定我的auth中间件将添加到请求中:user_id或用户模型本身,如何将可选的full_user参数传递给router?使用中间件示例:

.route("/", post(some_handlers::some_handler::post_smth),
        )
        .route_layer(middleware::from_fn_with_state(
            client.clone(),
            auth_middleware::auth,
        ));

我有这样的认证中间件:

pub async fn auth<B>(
    State(client): State<Client>,
    mut req: Request<B>,
    next: Next<B>,
) -> Result<Response, StatusCode> {
    let auth_header = match req.headers().get(http::header::AUTHORIZATION) {
        Some(header) => header.to_str().ok(),
        None => None,
    };

    let jwt_secret = std::env::var("JWT_SECRET").map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    let token = match auth_header {
        Some(token) => token,
        None => return Err(StatusCode::UNAUTHORIZED),
    };

    let token_claims = verify_token(token, &jwt_secret).map_err(|_| StatusCode::UNAUTHORIZED)?;

    let user_id = ObjectId::parse_str(&token_claims.sub).map_err(|_| StatusCode::UNAUTHORIZED)?;

    let collection: Collection<User> = client.database("Merume").collection("users");
    match collection.find_one(doc! {"_id": user_id}, None).await {
        Ok(Some(user)) => user,
        Ok(None) => return Err(StatusCode::UNAUTHORIZED),
        Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR),
    };

    req.extensions_mut().insert(user_id);
    Ok(next.run(req).await)
}

尝试了类似的操作,但不起作用,因为此函数的参数不正确

.layer(middleware::from_fn_with_state(
    client.clone(),
    |req, next| auth(req, next, Some(true)),
));
xn1cxnb4

xn1cxnb41#

我错过了状态参数,因为@cdhowie在评论中很伤心。解决方案:

.route_layer(middleware::from_fn_with_state(
        client.clone(),
        |state, req, next| auth_middleware::auth(state, req, next, Some(false)),
    ));

相关问题