2017-02-01 105 views
0

我有一個使用axios庫處理請求的React應用程序。因此,按照接下來的文章:微軟登錄oauth2問題

How to login with username/password using OAuth2 and microsoft login and HTTP request

我可以在郵差執行的操作。

然後,我成立了愛可信庫進行POST

const dataForBody = `${'grant_type=password&' + 
     'username='}${encodeURI(userName)}&` + 
     `password=${encodeURI(userPassword)}&` + 
     `client_id=${encodeURI(clientID)}&` + 
     `resource=${encodeURI('https://graph.microsoft.com')}&` + 
     `client_secret=${encodeURI(clientSecret)}`; 
const messageHeaders = { 
    'Content-Type': 'application/x-www-form-urlencoded' 
}; 

axios({ 
    method: 'post', 
    url: 'https://login.microsoftonline.com/{tenant}/oauth2/token', 
    headers: messageHeaders, 
    data: dataForBody, 
}) 
    .then((response) => { 

    }); 

,但我得到了以下錯誤:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://login.microsoftonline.com/ {tenant}/oauth2/token. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

我嘗試添加:

'Access-Control-Allow-Origin': 'https://login.microsoftonline.com', 

的頭,但它沒有奏效。

因此,添加Allow-Control-Allow-Origin: *​​​鉻擴展修復了我的問題。

事情是,我的應用程序將在azure上發佈,因此我在其他Web瀏覽器上測試了該請求,但它無效。所以我不希望我的用戶安裝擴展。

我的要求有問題嗎?爲什麼郵差可以做到這一點,而無需設置標題?

是否有其他方法來實現它?

PS:我讀了關於使用adal.js,但我不想使用微軟的登錄屏幕,因爲我知道用戶和通過的應用程序,我想避免手動登錄。

回答

3

您面臨的問題是由於您試圖通過AJAX調用令牌端點,而由於缺少CORS頭,AJAX不會接受它。您無法添加它,它從Azure AD的響應中缺失。

您需要做的不是從令牌端點獲取訪問令牌,而必須使用OAuth隱式授權流程。該流程允許您直接在授權階段獲取令牌,並專門爲基於JavaScript的應用程序設計。更多的信息在這裏:https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-dev-understanding-oauth2-implicit-grant

這意味着您不能像現在這樣使用密碼授權流程,除非您從後端而不是前端撥打電話。