【问题标题】:Request with URL that includes credentials使用包含凭据的 URL 的请求
【发布时间】:2017-12-17 10:49:56
【问题描述】:

我正在尝试获取 curl 并从 API 获取 JSON。

curl -XPOST -d "grant_type=password" -d "username=admin@admin.admin" \
    -d "password=admin" "web_app@localhost:8081/oauth/token"

当我在终端中使用 curl 时,一切正常,但尝试使用 fetch 时,我收到底部提到的错误消息。

fetch("http://web_app@localhost:8081/oauth/token", {
        credentials: 'include',
        body: "grant_type=password&username=admin@admin.admin&password=admin",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        method: "POST"
    }

这是我得到的错误:

TypeError: http://web_app@localhost:8081/oauth/token 是一个带有 嵌入式凭据。

我做错了吗?

【问题讨论】:

    标签: api reactjs curl fetch-api


    【解决方案1】:

    不能使用https://user:pass@host.com表单,需要设置Authorization http Header:

    var headers = new Headers();
    
    headers.append('Authorization', 'Basic ' + btoa(username + ':' + password));
    fetch('https://host.com', {headers: headers})
    

    btoa 将 'user:pass' 编码为 base64 编码字符串。您可以在 MDN 上找到 btoa 功能可用性(简而言之:它适用于 IE 10 及更高版本)。

    【讨论】:

    • 这是什么原因?
    • @felixfbecker 我不是 100% 确定,但这可能是出于安全原因的 b/c……您不允许将 auth-url 存储到缓存存储 api 中。如果服务人员可以读取request.url,那么这也会在javascript上下文中受到谴责,但是是什么阻止了你读取标题?我也想知道这种不允许的确切原因
    猜你喜欢
    • 2022-01-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 2017-12-15
    • 2017-12-19
    • 2019-12-04
    • 1970-01-01
    相关资源
    最近更新 更多