测试 javascript 网络应用 - 401(未授权)错误

Testing javascript web app - 401 (Unauthorized) error

我一直在努力理解 this link 中给出的示例:

我已经按照相同的方式为 outlook 创建了 office 应用程序以访问 office 365 Outlook APIs The link

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

我得到的错误是

  1. XMLHttpRequest cannot load https://outlook.office365.com/api/v1.0/me/messages. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:8080' is therefore not allowed access. The response had HTTP status code 401. - I get this error when CORS is not allowed.

  2. GET https://outlook.office365.com/api/v1.0/me/messages 401 (Unauthorized) - I get this error when I enable CORS.

我如何使用 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>

您尝试遵循的示例不是针对加载项,而是针对使用 Office 365 API 的 JavaScript 网络应用程序。我相信有一个使用 Office 365 APIs 的加载项是可能的,但这不是您所关注的示例所做的。

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

此外,我注意到您将 resource 变量更改为 https://graph.windows.net/, which is incorrect for the Mail API anyway. You'll need to set that to https://outlook.office365.com.