I can currently use Postman to retrieve an "access_token" but I'm trying to replicate this in ajax (for the purpose of playing around with a few things in jsfiddle)
So in Postman, I have:
If I run that I get a response containing my access_token:
I'm trying to replicate this in ajax and after some help on here I was able to create the following script:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
data: JSON.stringify({
grant_type: 'client_credentials',
client_id: '***',
client_secret: '***',
resource: 'https://analysis.windows.net/powerbi/api'
}),
success: data => {
console.log(data.access_token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
This returns an error each time in the console:
I feel like I'm close but can not figure it out
Your POST is x-www-form-urlencoded but your ajax data is a json string.
When data is passed as a string it should already be encoded using the correct encoding for contentType, which by default is application/x-www-form-urlencoded.
When data is an object, jQuery generates the data string from the object's key/value pairs unless the processData option is set to false. For example, { a: "bc", d: "e,f" } is converted to the string "a=bc&d=e%2Cf". If the value is an array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). For example, { a: [1,2] } becomes the string "a%5B%5D=1&a%5B%5D=2" with the default traditional: false setting.
https://api.jquery.com/jquery.ajax/
So try removing the JSON.stringify and just passing the POJO. e.g.
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
data: {
grant_type: 'client_credentials',
client_id: '***',
client_secret: '***',
resource: 'https://analysis.windows.net/powerbi/api'
},
success: data => {
console.log(data.access_token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});