【问题标题】:Requesting OAuth2 Token With AJAX使用 AJAX 请求 OAuth2 令牌
【发布时间】:2018-08-13 14:40:01
【问题描述】:

我正在尝试使用 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 令牌)

【问题讨论】:

标签: javascript jquery ajax oauth-2.0


【解决方案1】:

确定 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);
    }
});

【讨论】:

    【解决方案2】:

    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()));
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2014-11-05
      • 1970-01-01
      • 2013-04-11
      • 2019-09-13
      • 2012-06-08
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 2023-01-14
      相关资源
      最近更新 更多