亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

嘗試使用 JavaScript 從 azure 獲取訪問令牌時無法加載響應數據

嘗試使用 JavaScript 從 azure 獲取訪問令牌時無法加載響應數據

慕絲7291255 2023-12-14 15:29:39
我想為我在 azure 上注冊的應用程序獲取訪問令牌。為此,我編寫了一段代碼來訪問其余 API。這是我的代碼:<html><head>  <title>Test</title>     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>  <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.12/js/adal.min.js"></script>  <script src="/static/powerbi.js"></script>  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>          </head><body>  <div id="captionArea">    <h1>Power BI Embed test</h1>  </div>  <div id="embedContainer" style="height:500px">  </div>   <script>    (function () {    var reportId = 'xxxxxxxxxx'    var groupId  = 'xxxxxxxxxx'   //workspace_id    var datasetId = 'xxxxxxxxxx'           var settings = {  "url": "https://login.microsoftonline.com/common/oauth2/token",  "method": "POST",  "crossDomain": true,  "dataType": 'jsonp',  "timeout": 0,  "headers": {    "Content-Type": "application/x-www-form-urlencoded"  },  "data": {    "client_id": "********",    "username": "***",    "password": "***",    "grant_type": "password",    "resource": "https://analysis.windows.net/powerbi/api"  }};$.ajax(settings).done(function (response) {  console.log(response);}); }());  </script></body></html>之后,我得到了回應。在控制臺的標題部分下,我得到了狀態:200和請求方法:GET,但在我的代碼中,請求方法是“POST”,并且在響應部分中,它顯示“此請求沒有可用的響應數據”:我不知道為什么我沒有得到任何響應以及我的請求方法如何從“POST”更改為“GET”?
查看完整描述

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權限。

https://img1.sycdn.imooc.com/657aaf4c0001754212970418.jpg

下一步是獲取此范圍的訪問令牌。

https://img1.sycdn.imooc.com/657aaf600001b44514750376.jpg

有了這個訪問令牌,調用 api 就可以了。

https://img1.sycdn.imooc.com/657aaf7300011dc115380568.jpg

查看完整回答
反對 回復 2023-12-14
?
幕布斯7119047

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);

? ? })

? })

}


查看完整回答
反對 回復 2023-12-14
  • 2 回答
  • 0 關注
  • 183 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號