Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用AJAX请求OAuth2令牌_Javascript_Jquery_Ajax_Oauth 2.0 - Fatal编程技术网

Javascript 使用AJAX请求OAuth2令牌

Javascript 使用AJAX请求OAuth2令牌,javascript,jquery,ajax,oauth-2.0,Javascript,Jquery,Ajax,Oauth 2.0,我正在尝试使用AJAX请求令牌。这将仅在本地主机上用于发出请求。我有密码: $.ajax({ url: "TOKEN URL HERE", beforeSend: function(xhr) { xhr.setRequestHeader("grant_type", "client_credentials"); xhr.setRequestHeader("client_id", "ENTER CLIENT ID"); xhr.setRequestHeader("cl

我正在尝试使用AJAX请求令牌。这将仅在本地主机上用于发出请求。我有密码:

$.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);
  }
});

但是,它不起作用。这是正确的方法还是参数不正确?(或者OAuth2令牌请求在AJAX/JQuery/JS中是不可能的)

您确定,授权类型、客户机id、客户机机密应该通过头而不是负载传递吗

尝试从标题中删除它们(左接受,仅限内容类型),然后添加“数据”属性和其余参数

诸如此类:

$.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);
    }
});

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

如果对你有用,请检查一下