簡體   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