测试javascript web app - 401(未经授权)错误

时间:2015-08-10 20:04:56

标签: javascript outlook office365 office-app

我一直在尝试理解this链接中提供的示例:

我已经创建了Outlook的Office应用程序,用于访问Office 365 Outlook API The link

我使用Napa Dev Tools创建了应用程序。

我得到的错误是

  
      
  1. XMLHttpRequest无法加载https://outlook.office365.com/api/v1.0/me/messages。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“https://localhost:8080”访问。响应具有HTTP状态代码401. - 当不允许CORS时,我收到此错误。

  2.   
  3. 获取https://outlook.office365.com/api/v1.0/me/messages 401(未经授权) - 启用CORS时出现此错误。

  4.   

如何使用Outlook REST API调用并在本地测试应用程序?

对此有任何帮助非常感谢!谢谢!

编辑: 修改了带有“// changed”注释的代码以使示例正常工作 -

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>O365 CORS Sample</title>
<style>
body {
    font-family:'Segoe UI';
}

.paddedElement {
    margin-top: 5px;
}

.hidden {
visibility: hidden;
}
</style>
</head>
<body>
<h2>O365 CORS Sample</h2>
<label for="TxtOauthToken">OAuth Token:</label>
<input type="text" id="TxtOauthToken" size="80" />
<br />
<label for="endpointUrl">Endpoint URL:</label>
<input type="text" id="endpoint" size="80" />
<br />
<input type="button" class="paddedElement" id="getToken" value="Get Token">
<input type="button" class="paddedElement" id="doCors" value="Make CORS Request" visibility="hidden" />
<br />
<br />
<label for="results" class="hidden paddedElement" id="resultHeading">Results:</label>
<br />
<label id="debugMessage"></label>
<pre id="results"></pre>
<script type="text/javascript">
(function (window) {
 var isCorsCompatible = function() {
 try
 {
 var xhr = new XMLHttpRequest();
 xhr.open("GET", getEndpointUrl());
 xhr.setRequestHeader("authorization", "Bearer " + token);
 xhr.setRequestHeader("accept", "application/json");
 xhr.onload = function () {
 // CORS is working.
 console.log("Browser is CORS compatible.");
 }
 xhr.send();
 }
 catch (e)
 {
 if (e.number == -2147024891)
 {
 console.log("Internet Explorer users must use Internet Explorer 11 with MS15-032: Cumulative security update for Internet Explorer (KB3038314) installed for this sample to work.");
 }
 else
 {
     console.log("An unexpected error occurred. Please refresh the page.");
 }

 }
 };

 var urlParameterExtraction = new (function () {
         function splitQueryString(queryStringFormattedString) {
         console.log("Query: " + queryStringFormattedString);
         var split = queryStringFormattedString.split('&');

         // If there are no parameters in URL, do nothing.
         if (split == "") {
         return {};
         }

         var results = {};

         // If there are parameters in URL, extract key/value pairs.
         for (var i = 0; i < split.length; ++i) {
         var p = split[i].split('=', 2);
         if (p.length == 1)
         results[p[0]] = "";
         else
         results[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
         }

         return results;
         }

         // Split the query string (after removing preceding '#').
         this.queryStringParameters = splitQueryString(window.location.hash.substr(1));
 })();

 var token = urlParameterExtraction.queryStringParameters['access_token'];

 if (token == undefined) {
     document.getElementById("TxtOauthToken").value = "Click \"Get Token\" to trigger sign-in after entering the endpoint you want to use.";

     document.getElementById("doCors").style.visibility = "hidden";
 }
 else {
     document.getElementById("TxtOauthToken").value = token;
     document.getElementById("doCors").style.visibility = "visible";
     document.getElementById("getToken").style.display = "none";
 }

 // Constructs the authentication URL and directs the user to it.
 function requestToken() {
     // Change clientId and replyUrl to reflect your app's values
     // found on the Configure tab in the Azure Management Portal.
     var clientId    = 'd18f9842-eec8-4d81-93e4-24ced3d59199';   //Changed
     var replyUrl    = 'https://localhost:8080/echo';  //Changed
         var resource    = "https://graph.windows.net/"; //Changed

     var authServer  = 'https://login.windows.net/common/oauth2/authorize?';
         //var endpointUrl = getEndpointUrl();
         var endpointUrl = 'http://outlook.office365.com/api/v1.0/me/messages';  //Changed

     var responseType = 'token';

     var url = authServer +
         "response_type=" + encodeURI(responseType) + "&" +
         "client_id=" + encodeURI(clientId) + "&" +
         "resource=" + encodeURI(resource) + "&" +
         "redirect_uri=" + encodeURI(replyUrl);

     window.location = url;
 }

 document.getElementById("getToken").onclick = requestToken;

 function getEndpointUrl() {
     return document.getElementById("endpoint").value;
 }

 function getFilesFromO365() {
     document.getElementById("results").textContent = "";

     // Check browser compatbility. Check console output for details.
     isCorsCompatible();

     try
     {
         var xhr = new XMLHttpRequest();
         xhr.open("GET", getEndpointUrl());

         // The APIs require an OAuth access token in the Authorization header, formatted like this: 'Authorization: Bearer <token>'.
         xhr.setRequestHeader("Authorization", "Bearer " + token);

         // Process the response from the API.
         xhr.onload = function () {
             document.getElementById("resultHeading").style.visibility = "visible";

             if (xhr.status == 200) {
                 var formattedResponse = JSON.stringify(JSON.parse(xhr.response), undefined, 2);
                 document.getElementById("results").textContent = formattedResponse;
             } else {
                 document.getElementById("results").textContent = "HTTP " + xhr.status + "<br>" + xhr.response;
             }
         }

         // Make request.
         xhr.send();
     }
     catch (err)
     {
         document.getElementById("resultHeading").style.visibility = "visible";
         document.getElementById("results").textContent = "Exception: " + err.message;
     }
 }

 document.getElementById("doCors").onclick = getFilesFromO365;

})(window);
</script>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

您尝试遵循的示例不是用于加载项,而是用于使用Office 365 API的JavaScript Web应用程序。我相信可以使用一个使用Office 365 API的加载项,但这不是您所关注的示例。

在任何情况下,都可以通过在Azure AD中为您的应用设置正确的权限来修复您获得的401。您所关注的示例是使用Files API,因此它在使用Azure AD注册您的应用部分的步骤10中设置读取用户的文件权限。对于您的情况,您需要添加 Office 365 Exchange Online 应用程序,然后选择正确的权限。

此外,我注意到您已将资源变量更改为 https://graph.windows.net/ ,这对于Mail API来说是不正确的。您需要将其设置为 https://outlook.office365.com