如何使用密码和用户名来获取访问令牌?

时间:2015-03-25 12:04:47

标签: javascript jquery ajax json token

 $.ajax({
            url: 'https://api-ssl.bitly.com/oauth/access_token',

            type: 'POST',
            contentType: 'application/x-www-form-urlencoded',
            dataType: 'json',

            data: { Authorization: "Basic " + btoa('myusername' + ":" + 'mypassword@123') },
            success: function (result) {
                console.log(result);
            },
            error: function () {
                alert("Cannot get data");
            }
        });

我试图通过提供用户名和密码从bitly api获取访问令牌,但它显示invalid_client_authorization错误。有没有人有相同的想法?

有点文档:http://dev.bitly.com/authentication.html#resource_owner_credentials

2 个答案:

答案 0 :(得分:0)

您正在将您的用户名与授权标题联系起来。

您的授权和内容类型应该放在header对象中。

jquery ajax方法没有'type'属性,你可能意味着'方法'。

此外,您不能同时发送dataType:'json'并将内容类型设置为'application / x-www-form-urlencoded'

 $.ajax({
        url: 'https://api-ssl.bitly.com/oauth/access_token',

        methdo: 'POST',
        contentType: '',
        dataType: 'json',
        headers: {
            'Authorization' : 'Basic ' + [INSERT YOUR HASH HERE],
            'Content-Type' : 'application/x-www-form-urlencoded',
        }
        data: { $.serialize({
            username: YOURUSERNAME,
            password: YOURPASSWORD
        })},
        success: function (result) {
            console.log(result);
        },
        error: function () {
            alert("Cannot get data");
        }
    });

这应该这样做

答案 1 :(得分:0)

修正@goncalomarques回答:

  • 删除了顶级" contentType"和" dataType"
  • 删除了数据对象(否则用户名和密码将以明文形式发送,除了标题中的哈希用户名和密码外)
  • 更名为" methdo"到"方法"
  • 明确使用btoa()获取Base 64编码的哈希值(请注意,在旧的IE版本中不起作用)



$.ajax({
  url: 'https://api-ssl.bitly.com/oauth/access_token',
  method: 'POST',
  headers: {
    'Authorization': 'Basic ' + btoa(YOURUSERNAME + ':' + YOURPASSWORD),
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  success: function(result) {
    console.log("success");
    console.log(result);
  },
  error: function(response) {
    console.log("Cannot get data");
    console.log(response);
  }
});




注意: 我有这个例子,但由于交叉原因异常,无法使用内置的Stackoverflow编辑器("运行代码段")。

相关问题