当前在访问具有 autherize 属性并注册到 Azure AD 的 Web API Controller 时遇到问题。目前,我已成功从 ADAL.JS 获取 token ,现在正在尝试对测试 Webapi 进行 ajax 调用,该测试 Webapi 将为我的 Office-Addin 应用程序执行后端服务。我已经尝试过我将描述的场景。
第一个场景: 我创建了单独的 Web 应用程序条目 Azure 管理门户,一个用于我的办公室添加应用程序,以便我可以获得 token ,另一个用于我的 Web api,以便我可以将其锁定。然后,我向我的 webapi 授予了我的 office-add 应用程序的权限,以便我的 office-Add 能够与我的 web api 进行对话。我收到未经授权的 401 状态。
第二参议员:
由于我未经授权,我继续在我的 Azure 管理门户中创建一个新应用程序,并使用 ADAL.js 获取 token ,但是当我对与我的办公室共享相同客户端号码的 webapi 进行相同的调用时 -插件应用程序我仍然得到未经授权的 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.");
});
}
});
};
}
最佳答案
我有点困惑你调用的 API 是 “https://localhost:44334/api/Values/Get”,但获取token的资源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
此示例演示了如何使用 ADAL for JavaScript 来保护基于 AngularJS 的单页应用程序(通过 ASP.NET Web API 后端实现)。
关于javascript - Office 添加未对 Webapi 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36947287/