2017-09-16 110 views
1

我有一個絕對可怕的時間試圖使用Outlook 365 API。我的用例非常簡單:製作一個腳本,每小時運行一次,以提取有關用戶日曆的信息。Outlook 365 API - 身份驗證

我的腳本在Python中運行,我能夠獲得一個令牌,但我無法獲取用戶的事件。我明顯在Microsoft Application Registration Portal中註冊了我的應用程序,並獲得了Calendar.read應用程序權限。管理員還通過訪問/adminconsent端點進行了同意。

這裏是我的代碼,以獲得令牌(文檔here):

url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token' 
data = { 
    'grant_type': 'client_credentials', 
    'client_id': app_id, 
    'scope': 'https://graph.microsoft.com/.default', <--- Really not sure about this here 
    'client_secret': client_secret, 
} 
r = requests.post(url, data=data) 
token = r.json().get('access_token') 

是我該什麼範圍使用?該文件只提到以上的文件。

,並讀取用戶的日曆:

url = 'https://outlook.office.com/api/v2.0/users/{}/events'.format(user_email) 
headers = { 
    'Authorization': 'Bearer {}'.format(token) 
} 
r = requests.get(url, headers=headers) 

同樣,我真的不知道該users/{user_email}/部分。我閱讀了一些關於stackoverflow的人,他做了類似的事情,但在文檔的任何地方找不到它。

我能夠得到一個訪問令牌,但我得到嘗試讀取用戶的日曆時出現以下錯誤:

響應[401]

的訪問令牌使用的認證方法獲取的太弱,無法訪問此應用程序。提出的認證強度是1,要求是2.

請哦請stackoverflow,幫幫我。我花了太多的時間來完成這個非常簡單的任務。

回答

0

我終於找到它了。我非常接近。

我不得不使用Microsoft Graph API端點代替Outlook統一API端點。

最終的代碼如下所示:

import requests 

# Get a token 
url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token' 
data = { 
    'grant_type': 'client_credentials', 
    'client_id': app_id, 
    'scope': 'https://graph.microsoft.com/.default' 
    'client_secret': client_secret, 
} 
r = requests.post(url, data=data) 
token = r.json().get('access_token') 

# ... 

# Use the token using microsoft graph endpoints 
url = 'https://graph.microsoft.com/v1.0/users/{}/events'.format(user_email) # can also use the user_id (e.g. 12345-abcde-...) 
headers = { 
    'Authorization': 'Bearer {}'.format(token) 
} 
r = requests.get(url, headers=headers) 

微軟的文檔真的需要澄清。它有太多不同的API來做非常類似的事情。

+0

感謝您的反饋Fabrice。 Graph絕對是推薦使用的API。它實際上使用封面下的Outlook端點。我們在這裏有一個文檔,試圖解釋不同之處以及爲什麼您可以選擇一個:https://docs.microsoft.com/en-us/outlook/rest/compare-graph-outlook。我們正在努力將REST API的故事統一爲超級清晰,Graph是首選方式。 –

+0

很酷。感謝您的評論。我想那是你正試圖從一個版本轉換到另一個版本的那個時間點,因此是我最後一個短語。 –