尝试使用JavaScript从azure获取访问令牌时加载响应数据失败

尝试使用JavaScript从azure获取访问令牌时加载响应数据失败,javascript,html,jquery,azure,powerbi-embedded,Javascript,Html,Jquery,Azure,Powerbi Embedded,我想为我在azure上注册的应用程序获取访问令牌。为此,我编写了一段代码来访问RESTAPI 这是我的代码: <html> <head> <title>Test</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src=&q

我想为我在azure上注册的应用程序获取访问令牌。为此,我编写了一段代码来访问RESTAPI

这是我的代码:

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

试验
功率双嵌入测试
(功能(){
var reportId='xxxxxxxxx'
var groupId='xxxxxxxxx'//工作区\u id
var datasetId='xxxxxxxxx'
变量设置={
“url”:”https://login.microsoftonline.com/common/oauth2/token",
“方法”:“发布”,
“跨域”:正确,
“数据类型”:“jsonp”,
“超时”:0,
“标题”:{
“内容类型”:“应用程序/x-www-form-urlencoded”
},
“数据”:{
“客户id”:“*******”,
“用户名”:“***”,
“密码”:“***”,
“授权类型”:“密码”,
“资源”:https://analysis.windows.net/powerbi/api"
}
};
$.ajax(设置).done(函数(响应){
控制台日志(响应);
}); 
}());
在这之后,我得到了回应。在控制台的header部分下,我得到了status:200和request method:GET,但在我的代码中,request method是“POST”,在response部分,它显示“此请求没有可用的响应数据”:


我不知道,为什么我没有收到任何响应,我的请求方法如何从“POST”更改为“GET”?

您的数据类型为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);
    })
  })
}

文件
此示例使用隐式授权流获取访问令牌
登录
getAccessToken
getApiResponse
请登录以查看您的个人资料并阅读您的邮件
accesstoken:
api响应:
常量msalConfig={
认证:{
客户ID:“

下一步是获取具有此作用域的访问令牌。

使用这个访问令牌,调用api,它就会工作。

我以前的想法和你的想法一样,只是发送一个AJAX请求来获取访问令牌。当然,我失败了。我想这会对你有所帮助。我只是想和你核实一下上述方法是否有用?不,Satya V.没有帮助。感谢你的回复。使用此解决方案,我遇到了一个错误。错误是“InteractionRequiredAuthError:AADSTS65001:用户或管理员未同意使用ID为“xxxxxx”且名为“xxxxx powerBI Embed Test1”的应用程序。请为此用户和资源发送交互授权请求。"您能帮我一下吗?我的代码使用隐式授权流获取访问令牌并调用API,因此在创建azure ad应用程序后,我还需要设置API权限,并确保已在身份验证标记中签入“访问令牌”。我解决了这一问题。需要在Microsoft graph API中添加mail.read权限。只需使用登录即可您的管理员帐户并转到应用程序注册,然后选择API权限并单击添加权限我获得了访问令牌,但此访问令牌未能获得嵌入令牌。它返回403禁止403表示您的应用程序没有访问API的权限。因此,如果要调用“powerbi UserState.ReadWrite.All”,则需要添加此API权限,下一步要获取具有此作用域的访问令牌,然后可以执行此操作。
<!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>