我试图使用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令牌请求)
答案 0 :(得分:0)
确定,grant_type,client_id,client_secret应该通过标头而不是有效负载传递吗?
尝试从标题中删除它们(左接受,仅限内容类型),然后使用其余参数添加“data”属性。
类似的东西:
$.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);
}
});
答案 1 :(得分:0)
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()));
}
});