繁体   English   中英

如何通过在 JavaScript 中使用 POST 方法获取 API 的访问令牌?

[英]How to get access token for an API by using POST method in JavaScript?

我想获取使用 OAuth2 凭据的 API。 API 的文档列出了以下内容:

Request access token:

POST: auth/access_token

Url Parms:
grant_type    : "client_credentials"
client_id     :  Client id
client_secret :  Client secret

我从中想到的是,我需要将 JSON 对象作为字符串发送,所以我在 JavaScript 中尝试了这个。

var xhr = new XMLHttpRequest();
    xhr.open("POST","url for the api",false);
    
    var obj = {
       
       "POST": "auth/access_token",
       "Url Parms": [   
          {
             "grant_type":'\"client_credentials\"',
             "client_id": "My Client id",
             "client_secret": "My Client secret"
          }
       ]
    };
    
    var clientcred = JSON.stringify(obj);
    xhr.send(obj);

所有这些给了我一个 JSON,它说我犯了一个错误。

{"error":"invalid_request","error_description":"The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the \"grant_type\" parameter."}

由于“同源策略”,该代码实际上甚至不起作用。 我使用了一个扩展来解决这个问题。 但我已经完成了。 我想不通。 我需要学习像php这样的东西吗? 我如何获得我的访问令牌。

编辑:

它可能需要 URL 中的参数,因此 POST auth/access_token?grant_type=client_credentials&client_id=id‌ &client_secret=clien‌ t_secret 或 POST auth/access_token/client_credentials/id/client_secret – Sara Tibbetts 8 小时前

这做到了。 我醒来,第一件事就是尝试,它奏效了。 非常感谢@Sara Tibbetts 和所有试图帮助我的人。

编辑2:

扩展是一个糟糕的解决方法,从那时起我了解了跨源资源共享。 我应该从服务器调用 API 而不是在客户端调用,这实际上也是安全的。

这就是我在一个工作 Prod 程序中的做法(它使用的是我之前得到的授权码——但没关系,只是不同的参数——用客户端秘密要求替换我的具有授权码的东西,并给出这是一个尝试..我认为你只是太努力了。

var xhr = new XMLHttpRequest();

我使用一个字符串作为我的参数:

var data =
'resource=[my resource]' +
'&client_id=' + clientId +
'&code=' + authCode +
'&grant_type=authorization_code' +
'&response_type=token';
var dataFinal = encodeURI(data);

然后我将其发布为:

xhr.open('POST', url, true);
xhr.withCredentials = true;
xhr.setRequestHeader('Access-Control-Allow-Origin', '[something]');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
        //do something
    }
}
xhr.send(dataFinal);

您可以尝试以下操作。 实际上需要将 json 设置为 data 属性。

$.ajax({
type: 'POST',
url: 'https://url.com',
crossDomain: true,
data: JSON.stringify({grant_type    : "client_credentials",
    client_id     :  "My Client id",
    client_secret :  "My Client secret"}),
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
    console.log(responseData);
},
error: function (responseData, textStatus, errorThrown) {
    alert('POST failed.');
}});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM