简体   繁体   中英

how to get access token from bitly using password and username?

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

I am trying to get access token from bitly api by providing username and password but it is showing invalid_client_authorization error. Does any one have idea on the same?

Bitly documentation : http://dev.bitly.com/authentication.html#resource_owner_credentials

You are concatenating your username with your authorization header.

Your authorization and content-type should go in the headers object.

There is no 'type' property on jquery ajax method, you probably meant 'method'.

Also, you can't send both dataType:'json' and set the content-type to '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");
        }
    });

This should do it

Fixed @goncalomarques answer:

  • Removed top level "contentType" and "dataType"
  • Removed data object (otherwise username and password is sent as clear text, in addition to the hashed username and password in the header)
  • renamed "methdo" to "method"
  • Explicitly used btoa() to get Base 64 encoded hash (be aware, does not work in older IE versions)

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


Note: I have this example working, but was unable to get it working with the built-in Stackoverflow editor ("Run snippet") due to cross origin exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM