2016-04-29 54 views
0

當前訪問具有authenticrize屬性並註冊到Azure AD的web api控制器時出現問題。目前我正在從ADAL.JS成功獲取令牌,現在正在嘗試對測試WebAPI進行ajax調用,該WebAPI將爲我的Office-Addin應用執行後端服務。我試圖描述我將要描述的場景。辦公室加入不對Webapi進行身份驗證

第一種情景: 我創建了用於分隔Web應用程序條目的Azure管理門戶,一個用於我的辦公室添加應用程序以便我可以獲取令牌,另一個用於我的web API,以便將其鎖定。然後,我爲我的辦公室添加應用程序到我的webapi,以便我的辦公室 - 添加與我的web api交談。我的401狀態未經授權。

二塞納里奧:

因爲我得到授權我接着提出了一個新的應用程序在我的Azure管理門戶網站,並獲得與ADAL.js令牌,但是當我做對的WebAPI同一呼叫時共享與我的辦公室Addin應用程序相同的客戶端號碼仍然未獲得01狀態。

不知道我在做什麼錯,看起來像我已經嘗試了兩種可能的方式,但沒有人爲我工作。這是我的Java腳本

window.config = { 
tenant: variables.azureAD, 
clientId: variables.clientId, 
postLogoutRedirectUri: window.location.origin, 
endpoints: { 
    sharePointUri: "https://" + tenant + ".sharepoint.com", 
    ContentCenterApi: "https://localhost:44334" 
}, 
cacheLocation: "localStorage" 
}; 

    var authContext = new AuthenticationContext(config); 

    var isCallback = authContext.isCallback(window.location.hash); 
authContext.handleWindowCallback(); 

if (isCallback && !authContext.getLoginError()) { 
window.location =  authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST); 
} 


function GetSharepointList(e) { 
var authContext = new AuthenticationContext(config); 
var user = authContext.getCachedUser(); 


if (!user) { 
    authContext.login(); 
} 

else { 
    authContext.acquireToken(config.endpoints.sharePointUri, function (error, token) { 

     if (error || !token) { 
      console.log("ADAL error occurred: " + error); 
      return; 
     } 
     else { 
      var me = this; 
      //var SiteUrl = config.endpoints.sharePointUri + "/sites/Apps_Dev/ER_TestSite/"; 
      $.ajax({ 

       url: 'https://localhost:44334/api/Values/Get', 
       dataType: "json", 
       headers: { 
        "Authorization": "Bearer " + token, 
        "accept": "application/json;odata=verbose", 
       }, 
       success: function (data) { 
        handleData(data); 
       } 
      }).done(function (response) { 
       console.log("Successfully fetched list from SharePoint."); 
       // var items = response.d.results; 
       //$("#contentPreview").append(items[0]); 
      }).fail(function (error) { 
       console.log("Fetching list from SharePoint failed."); 
      }); 
     } 

    }); 
}; 
} 

回答

2

我有點困惑,你調用API是 「https://localhost:44334/api/Values/Get」,但資源ID獲取令牌是「config.endpoints.sharePointUri」。它應該是您在Azure AD上註冊的應用程序URI。

關於如何使用Azure AD保護Web API。下面的文章可能會給你一些幫助。

Protect a Web API using Bearer tokens from Azure AD

單頁應用演示(adal.js):active-directory-angularjs-singlepageapp

此示例演示了JavaScript的使用ADAL的用於保護基於單頁的應用程序的AngularJS,用一個ASP.NET Web API的後端實現。