Failed To Load Response Data When Tried To Get Access Token From Azure Using Javascript
I want to get an Access token for my registered application on azure. To do so I wrote a piece of code to hit the rest-API. This is my code:
Solution 1:
<!DOCTYPE html><html><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Document</title><scriptsrc="js/msal.js"></script></head><body><divstyle="font-size: 12px;">
this sample used implicit grant flow to get access token
</div><divstyle="margin-top: 15px; background-color: #DDDDDD;"><buttontype="button"id="signIn"onclick="signIn()">Sign In</button><buttontype="button"id="getAccessToken"onclick="getAzureAccessToken()">getAccessToken</button><buttontype="button"id="accessApi"onclick="accessApi()">getApiResponse</button><h5class="card-title"id="welcomeMessage">Please sign-in to see your profile and read your mails</h5><div><div>
accesstoken :
<divid="accesstoken"></div></div><divid="">
api response :
<divid="json"></div></div></div></div><scripttype="text/javascript">const msalConfig = {
auth: {
clientId: "<applicationId>",
authority: "https://login.microsoftonline.com/<tenantId>",
redirectUri: "http://localhost:8848/Demo0819/new_file.html",
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be storedstoreAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
}
};
const loginRequest = {
scopes: ["openid", "profile", "User.Read"]
};
//scope for getting accesstokenconstAzureMgmtScops ={
scopes:["https://management.azure.com/user_impersonation"]
}
//used for calling api const apiConf = {
endpoint:"https://management.azure.com/subscriptions/<subscriptionId>/providers/Microsoft.CostManagement/query?api-version=2019-11-01"
};
let accessToken = '';
const myMSALObj = newMsal.UserAgentApplication(msalConfig);
functionsignIn() {
myMSALObj.loginPopup(loginRequest)
.then(loginResponse => {
console.log("id_token acquired at: " + newDate().toString());
console.log(loginResponse);
if (myMSALObj.getAccount()) {
showWelcomeMessage(myMSALObj.getAccount());
}
}).catch(error => {
console.log(error);
});
}
functionshowWelcomeMessage(account) {
document.getElementById("welcomeMessage").innerHTML = `Welcome ${account.name}`;
}
functiongetAzureAccessToken(){
myMSALObj.acquireTokenSilent(AzureMgmtScops).then(tokenResponse => {
showAccesstoken(tokenResponse.accessToken)
accessToken = tokenResponse.accessToken;
// console.info("======the accesstoken is ======:"+tokenResponse.accessToken);// callMSGraph(apiConf.endpoint, tokenResponse.accessToken, showResult);
}).catch(function (error) {
console.log(error);
})
}
functionaccessApi(){
callMSGraph(apiConf.endpoint, accessToken, showResult);
}
functioncallMSGraph(endpoint, token, callback) {
const data = {
"type": "Usage",
"timeframe": "MonthToDate",
"dataset": {
"granularity": "Daily",
}
}
const headers = newHeaders();
const bearer = `Bearer ${token}`;
headers.append("Content-Type", "application/json");
headers.append("Authorization", bearer);
const options = {
body: JSON.stringify(data),
method: "POST",
headers: headers
};
console.log('request made to Graph API at: ' + newDate().toString());
fetch(endpoint, options)
.then(response => response.json())
.then(response =>callback(response, endpoint))
.catch(error =>console.log(error))
}
functionshowAccesstoken(data){
document.getElementById("accesstoken").innerHTML = JSON.stringify(data, null, 2);
}
functionshowResult(data){
document.getElementById("json").innerHTML = JSON.stringify(data, null, 2);
}
</script></body></html>
=========UPDATE======
E.g.
I wanna to call this api to get information 'https://api.powerbi.com/v1.0/myorg/groups' , so add api permission first.
Solution 2:
You have data type as JSONP. It simply creates a element to fetch data which has to be a GET request.
Reference : Send data using POST to JSONP request
How to use type: "POST" in jsonp ajax call
You could possible get the response by issuing a POST request and then use the obtained access token for the embed token.
Some thing like below :
var getAccessToken = function {
returnnewPromise(function(resolve, reject) {
var url = 'https://login.microsoftonline.com/common/oauth2/token';
var username = // Username of PowerBI "pro" account - stored in configvar password = // Password of PowerBI "pro" account - stored in configvar clientId = // Applicaton ID of app registered via Azure Active Directory - stored in configvar headers = {
'Content-Type' : 'application/x-www-form-urlencoded'
};
var formData = {
grant_type:'password',
client_id: clientId,
resource:'https://analysis.windows.net/powerbi/api',
scope:'openid',
username:username,
password:password
};
request.post({
url:url,
form:formData,
headers:headers
}, function(err, result, body) {
if(err) returnreject(err);
var bodyObj = JSON.parse(body);
resolve(bodyObj.access_token);
})
});
}
// -------------------------------------------var getEmbedToken = function(accessToken, groupId, reportId) {
returnnewPromise(function(resolve, reject) {
var url = 'https://api.powerbi.com/v1.0/myorg/groups/' + groupId + '/reports/' + reportId + '/GenerateToken';
var headers = {
'Content-Type' : 'application/x-www-form-urlencoded',
'Authorization' : 'Bearer ' + accessToken
};
var formData = {
"accessLevel": "View"
};
request.post({
url:url,
form:formData,
headers:headers
}, function(err, result, body) {
if(err) returnreject(err);
console.log(body)
var bodyObj = JSON.parse(body);
resolve(bodyObj.token);
})
})
}
Post a Comment for "Failed To Load Response Data When Tried To Get Access Token From Azure Using Javascript"