2 回答
TA贡献1829条经验 获得超7个赞
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/msal.js"></script>
</head>
<body>
<div style="font-size: 12px;">
this sample used implicit grant flow to get access token
</div>
<div style="margin-top: 15px; background-color: #DDDDDD;">
<button type="button" id="signIn" onclick="signIn()">Sign In</button>
<button type="button" id="getAccessToken" onclick="getAzureAccessToken()">getAccessToken</button>
<button type="button" id="accessApi" onclick="accessApi()">getApiResponse</button>
<h5 class="card-title" id="welcomeMessage">Please sign-in to see your profile and read your mails</h5>
<div>
<div>
accesstoken :
<div id="accesstoken">
</div>
</div>
<div id="">
api response :
<div id="json">
</div>
</div>
</div>
</div>
<script type="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 stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
}
};
const loginRequest = {
scopes: ["openid", "profile", "User.Read"]
};
//scope for getting accesstoken
const AzureMgmtScops ={
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 = new Msal.UserAgentApplication(msalConfig);
function signIn() {
myMSALObj.loginPopup(loginRequest)
.then(loginResponse => {
console.log("id_token acquired at: " + new Date().toString());
console.log(loginResponse);
if (myMSALObj.getAccount()) {
showWelcomeMessage(myMSALObj.getAccount());
}
}).catch(error => {
console.log(error);
});
}
function showWelcomeMessage(account) {
document.getElementById("welcomeMessage").innerHTML = `Welcome ${account.name}`;
}
function getAzureAccessToken(){
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);
})
}
function accessApi(){
callMSGraph(apiConf.endpoint, accessToken, showResult);
}
function callMSGraph(endpoint, token, callback) {
const data = {
"type": "Usage",
"timeframe": "MonthToDate",
"dataset": {
"granularity": "Daily",
}
}
const headers = new Headers();
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: ' + new Date().toString());
fetch(endpoint, options)
.then(response => response.json())
.then(response => callback(response, endpoint))
.catch(error => console.log(error))
}
function showAccesstoken(data){
document.getElementById("accesstoken").innerHTML = JSON.stringify(data, null, 2);
}
function showResult(data){
document.getElementById("json").innerHTML = JSON.stringify(data, null, 2);
}
</script>
</body>
</html>
=========更新======
例如
我想调用这个api来获取信息 'https://api.powerbi.com/v1.0/myorg/groups' ,所以先添加api权限。
下一步是获取此范围的访问令牌。
有了这个访问令牌,调用 api 就可以了。
TA贡献1794条经验 获得超8个赞
您的数据类型为 JSONP。它只是创建一个元素来获取必须是 GET 请求的数据。
您可以通过发出 POST 请求来获取响应,然后使用获得的访问令牌作为嵌入令牌。
像下面这样的事情:
var getAccessToken = function {
return new Promise(function(resolve, reject) {
var url = 'https://login.microsoftonline.com/common/oauth2/token';
var username = // Username of PowerBI "pro" account - stored in config
var password = // Password of PowerBI "pro" account - stored in config
var clientId = // Applicaton ID of app registered via Azure Active Directory - stored in config
var 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) return reject(err);
var bodyObj = JSON.parse(body);
resolve(bodyObj.access_token);
})
});
}
// -------------------------------------------
var getEmbedToken = function(accessToken, groupId, reportId) {
return new Promise(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) return reject(err);
console.log(body)
var bodyObj = JSON.parse(body);
resolve(bodyObj.token);
})
})
}
添加回答
举报