Office添加未对Webapi进行身份验证

时间:2016-04-29 20:55:14

标签: javascript ajax office365 adal office-js

目前在访问具有autherize属性并已注册到Azure AD的Web api控制器时遇到问题。目前我正在成功从ADAL.JS获取令牌,现在我正在尝试对测试Webapi进行ajax调用,该测试将为我的Office-Addin应用程序执行后端服务。我尝试过将要描述的场景。

第一种情景: 我创建了单独的Web应用程序条目Azure管理门户,一个用于我的办公室添加应用程序以便我可以获得一个令牌,而另一个用于我的web api我可以将其锁定。然后,我允许我的办公室添加应用程序到我的webapi,以便我的办公室 - 加入我的网络API。我未经授权获得401状态。

Second Senario:

由于我未经授权,我继续在我的Azure管理门户中创建一个新应用程序,并获得一个带有ADAL.js的令牌,但当我对与我的办公室共享相同客户编号的webapi进行相同的调用时 - Addin app我仍未获得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.");
            });
        }

    });
};
}

1 个答案:

答案 0 :(得分:2)

我对你调用的API有点困惑 “https://localhost:44334/api/Values/Get”,但获取令牌的资源ID是“config.endpoints.sharePointUri”。它应该是您在Azure AD上注册的App 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后端实现的。