如何通过传递秘钥使用 reqwest 添加基本授权头?

5

我正在使用 reqwest = { version = "0.11", features = ["json"] }


impl Client {
    pub fn new(/*endpoint: Url*/) -> Result<Client> {
        Ok(Client {
            client: reqwest::ClientBuilder::new().build()?,
        })
    }
}

let res = self
    .client
    .post(url)
    .header("Content-type", "application/x-www-form-urlencoded")
    .header("Authorization", "Basic".to_owned() + &secret)
    .send
    .await?;
let data = res.json::<Response>().await?;

我无法设置基本授权头部,代码报错"缺少身份验证凭据"。


很难回答你的问题,因为它没有包含一个 [MRE]。我们无法确定代码中存在哪些 crates(及其版本)、types、traits、fields等。如果可能的话,您可以在Rust Playground上尝试重现错误,否则可以在全新的Cargo项目中进行,然后[编辑]您的问题以包括额外的信息。这里有一些Rust特定的MRE提示,您可以使用它们来缩小您的原始代码以便在此处发布。谢谢! - Shepmaster
5
假设你的“秘密(secret)”已经正确编码,那么它似乎缺少在“Basic”后面加上一个空格。 - kmdreko
像netcat这样的基本HTTP调试工具显示了你发送了什么? - Shepmaster
@kmdreko 感谢您节省了我的调试时间。在测试时从未注意到的愚蠢错误是没有考虑“Basic”后面的空格。现在可以正常工作了。 - sum91
1个回答

8
根据上面的评论建议,在标题中"Basic"后添加了缺少的空格,解决了这个问题。
let res = self
    .client
    .post(url)
    .header("Content-type", "application/x-www-form-urlencoded")
    .header("Authorization", "Basic ".to_owned() + &secret)
    .send()
    .await?;

应该调用.send()而不是.send - simanacci
应该使用较新的 basic_auth 构建器。请参见此处的示例:https://github.com/seanmonstar/reqwest/discussions/1660 - ecoe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接