简体   繁体   中英

How to get access token for an API by using POST method in JavaScript?

The API I want to get credentials for uses OAuth2. The documentation for the API has this listed:

Request access token:

POST: auth/access_token

Url Parms:
grant_type    : "client_credentials"
client_id     :  Client id
client_secret :  Client secret

What I figured from this is that I need to send a JSON object as a string so I tried this in JavaScript.

var xhr = new XMLHttpRequest();
    xhr.open("POST","url for the api",false);
    
    var obj = {
       
       "POST": "auth/access_token",
       "Url Parms": [   
          {
             "grant_type":'\"client_credentials\"',
             "client_id": "My Client id",
             "client_secret": "My Client secret"
          }
       ]
    };
    
    var clientcred = JSON.stringify(obj);
    xhr.send(obj);

All this gave me was a JSON which said I made an error.

{"error":"invalid_request","error_description":"The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the \"grant_type\" parameter."}

The code actually doesn't even work because of 'same-origin policy'. I used an extension to get around that. But I am so done. I can't figure it out. Do I need to learn something like php? How do I get my access token.

Edit:

It might need the parameters in the URL, so POST auth/access_token?grant_type=client_credentials&client_id=id‌​&client_secret=clien‌​t_secret or possibly POST auth/access_token/client_credentials/id/client_secret – Sara Tibbetts 8 hours ago

This did it. I woke up and the first thing I tried and it worked. Thank you so much @Sara Tibbetts and everyone else who tried to help me.

Edit 2:

The extension was a poor workaround, since then I have learned about Cross Origin Resource Sharing. I should've made my API call from the server rather than doing it client side, which is actually secure as well.

This is how I'm doing it in a working Prod program (It is using an auth code that I get earlier - but it doesn't matter, it's just different parameters - replace my stuff that has auth code with client secret requirements and give it a try..I think you're just trying too hard.

var xhr = new XMLHttpRequest();

I use a string for my parameters:

var data =
'resource=[my resource]' +
'&client_id=' + clientId +
'&code=' + authCode +
'&grant_type=authorization_code' +
'&response_type=token';
var dataFinal = encodeURI(data);

Then I POST it as:

xhr.open('POST', url, true);
xhr.withCredentials = true;
xhr.setRequestHeader('Access-Control-Allow-Origin', '[something]');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
        //do something
    }
}
xhr.send(dataFinal);

You can try something like the below. Actually the json needs to be set to the data property.

$.ajax({
type: 'POST',
url: 'https://url.com',
crossDomain: true,
data: JSON.stringify({grant_type    : "client_credentials",
    client_id     :  "My Client id",
    client_secret :  "My Client secret"}),
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
    console.log(responseData);
},
error: function (responseData, textStatus, errorThrown) {
    alert('POST failed.');
}});

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