簡體   English   中英

使用 AJAX 請求 OAuth2 令牌

[英]Requesting OAuth2 Token With AJAX

我正在嘗試使用 AJAX 請求令牌。 這將僅在 localhost 上用於發出請求。 我有代碼:

$.ajax({
  url: "TOKEN URL HERE",
  beforeSend: function(xhr) {
    xhr.setRequestHeader("grant_type", "client_credentials");
    xhr.setRequestHeader("client_id", "ENTER CLIENT ID");
    xhr.setRequestHeader("client_secret", "ENTER CLIENT SECRET");
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("Accept", "application/json");
  },
  dataType: "json",
  //content-Type: "application/json",
  type: "POST",
  success: function(response) {
    token = response.access_token;
    expiresIn = response.expires_in;
  },
  error: function(errorThrown) {
    alert(errorThrown.error);
  }
});

但是,它不起作用。 這是正確的方法還是我的參數不正確? (或者是 AJAX/JQuery/JS 無法實現 OAuth2 令牌請求)

Piotr P 的回答對我不起作用。 作為數據的一部分發送時,我從中獲取令牌的客戶端不接受客戶端 ID 和憑據。 我不得不改用基本身份驗證。 這是對我有用的 ajax 調用。

$.ajax({
  "type": "POST",
  "url": "https://some.domain.com/oath/token",
  "headers": {
    "Accept": "application/json",
    "Authorization": "Basic " + btoa(username + ":" + password)
  },

  "data": {
    "grant_type": "client_credentials"
  },


  "success": function(response) {
    token = response.access_token;
    expiresIn = response.expires_in;
  },
  "error": function(errorThrown) {
    alert(JSON.stringify(errorThrown.error()));
  }
});

確定 grant_type、client_id、client_secret 應該由標頭而不是有效負載傳遞嗎?

嘗試從標頭中刪除它們(左接受,僅內容類型),然后添加帶有其余參數的“數據”屬性。

像這樣的東西:

$.ajax({
    url: "TOKEN URL HERE",
    beforeSend: function(xhr) {
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("Accept", "application/json");
    },
    dataType: "json",
    data: {
        client_id: "ENTER CLIENT ID",
        client_secret: "ENTER CLIENT SECRET",
        grant_type: "client_credentials"
    },
    type: "POST",
    success: function(response) {
        token = response.access_token;
        expiresIn = response.expires_in;
    },
    error: function(errorThrown) {
        alert(errorThrown.error);
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM