I am trying to obtain credentials for an API that uses OAuth2. The API documentation outlines the process as follows:
Request access token:
POST: auth/access_token
Url Parms:
grant_type : "client_credentials"
client_id : Client id
client_secret : Client secret
Based on this information, I attempted to send a JSON object 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);
However, I received an error message stating that my request was invalid.
{"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."}
Due to the 'same-origin policy' restriction, the code did not work as expected. After using an extension to bypass this, I still struggled to resolve the issue. Should I consider learning PHP? How can I successfully retrieve my access token?
Edit:
Adding the parameters directly to the URL like POST auth/access_token?grant_type=client_credentials&client_id=id&client_secret=client_secret seemed to solve the problem. Thank you @Sara Tibbetts for your suggestion.
Finally, after attempting it again the following day, it worked flawlessly. A big thank you to @Sara Tibbetts and everyone who offered assistance.
Edit 2:
I have come to realize that relying on the extension was not ideal, and I now understand the significance of Cross Origin Resource Sharing. Moving forward, making API calls from the server side is a more secure approach than doing so client-side.