Uncategorized

Office 365 API : CORS の使用

Outlook REST API (以降の https://outlook.office.com または https://outlook.office365.com) は 2022/11/30 に終了予定です。今後は Microsoft Graph (統一エンドポイント) を使用してください。

Office 365 API

(Skype API は こちら)

こんにちは。

Office 365 API が CORS に対応しましたので、AngularJS, React などでサーバー ロジックを使わずに呼び出せます。(CORS については「JSONP などクロス ドメイン (Cross-Domain) 問題の回避と諸注意」を参照。)
最近、Office 365 API の MyFiles (OneDrive for Business) と Site (SharePoint) で CORS 対応していましたが、BUILD のタイミングにあわせて Exchange (Mail / Calendar / Contact), Office 365 Unified API など、他の API でも対応しました。

JavaScript による Azure AD 連携 (OAuth Implicit Grant)」で紹介した方法で JavaScript を使って Access Token を取得し、この Access Token を使って下記の通り Office 365 API を呼び出します。(JavaScript のみで Office 365 API の呼び出しが可能です。)

<!DOCTYPE html><html><head>  <meta charset="utf-8" />  <meta http-equiv="X-UA-Compatible" content="IE=edge">  <title>CORS Test</title>  <meta name="viewport" content="width=device-width, initial-scale=1"></head><body>  <button id="btnLogin">Login !</button>  <button id="btnMail">Get Mail</button>  <div id="txtResult"></div>  <script>  var token;  (function () {if(location.hash) {  var hasharr = location.hash.substr(1).split("&");  hasharr.forEach(function(hashelem) {var elemarr = hashelem.split('=');if(elemarr[0] == 'access_token') {  token = elemarr[1];  document.getElementById('txtResult').textContent = 'Logged In !';}  }, this);}document.getElementById('btnLogin').onclick = function() {  location.href = 'https://login.microsoftonline.com/common/oauth2/authorize?response_type=token&client_id=cb830...&resource=https%3A%2F%2Foutlook.office365.com%2F&redirect_uri=https%3A%2F%2Flocalhost%2Ftest.html';}document.getElementById('btnMail').onclick = function() {  var xhr = new XMLHttpRequest();  xhr.open('GET', 'https://outlook.office365.com/api/v1.0/me/messages');  xhr.setRequestHeader("Authorization", "Bearer " + token);  xhr.onload = function () {if (xhr.status == 200) {  var formattedResponse = JSON.stringify(JSON.parse(xhr.response), undefined, 2);  document.getElementById("txtResult").textContent = formattedResponse;} else {  document.getElementById("txtResult").textContent ="HTTP " + xhr.status + "<br>" + xhr.response;}  }  xhr.send();}  }());</script></body></html>

Categories: Uncategorized

Tagged as: ,

Leave a Reply