对于调用SharePoint REST API的某些函数,我们的Excel加载项需要OAUTH令牌。
加载项使用功能区命令,但我们没有任务窗格。我们有以下代码从其他项目中获取令牌:
var dhi = dhi || {};
dhi.adal = (function (mod) {
var settings = {
clientId: "xxxyyyyzzzz",
url: "https://company.sharepoint.com"
};
mod.getToken = function () {
var dfd = $.Deferred();
//fix origin for IE
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
}
var configOptions = {
clientId: settings.clientId,
postLogoutRedirectUri: window.location.origin,
cacheLocation: 'localStorage',
}
window.authContext = new AuthenticationContext(configOptions);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
var user = authContext.getCachedUser();
if (!user) {
authContext.login();
} else {
var cachedToken = authContext.getCachedToken(user.profile.aud);
if (!cachedToken) {
authContext.login();
} else {
var url = settings.url;
var tok = authContext.acquireToken(url, function (error, token) {
console.log(error);
if (token != null) {
console.log(token);
sharedtoken = token;
dfd.resolve(token);
} else {
if (cachedToken != "" && cachedToken != null && cachedToken != undefined) {
dfd.resolve(cachedToken);
} else {
dfd.reject("Unable to obtain token. Please contact hotline@dhigroup.com with the following error : " + error);
}
}
});
}
}
return dfd.promise();
}
return mod;
})(dhi.adal || {});
并在functions.js
文件中(定义了功能区按钮的处理程序)我们称之为初始化:
(function () {
"use strict";
$(document).ready(function () {
dhi.adal.getToken.then(
function (token) {
sharedtoken = token;
Office.initialize = function (reason) {
// some code here
}
},
function (error) {
app.showNotification("Problem occured", error);
});
});
})();
我们正面临以下问题:
1)如果令牌已经缓存,则可以正常工作。但是,当需要调用authContext.login()
时,它会挂起(没有任何消息)。我们相信不知道在哪里显示登录对话框(在这个加载项的第一个版本中,我们使用了一个任务窗格,它在那里显示了登录页面,但是,由于几个原因我们需要使用命令。
2)我们必须在调用Office.initialize
之前调用它,否则它不起作用(我试图只将getToken
放到需要它的函数但没有成功) - 不明白为什么。这有一个副作用,我们必须总是调用getToken()
,当需要令牌时我也必须调用按钮操作
3)我尝试创建一个获取令牌的对话框,但还有一些其他问题 - adal.js
中的一些问题......
所以,我想问一下 - 是否有任何直接的方法如何从Office.jas中的Active目录中获取SharePoint令牌
如果有一些样品,它会对我们有很大帮助。
答案 0 :(得分:0)
没有用于获取SharePoint令牌的内置方法。
至于打开身份验证对话框,您应该使用Dialog API。有一个示例PowerPoint外接程序,它使用Dialog API对Graph进行身份验证:PowerPoint-Add-in-Microsoft-Graph-ASPNET-InsertChart。此处使用的主体和组件应轻松转换为Excel和SharePoint。
对于身份验证库,我建议您查看microsoft-authentication-library-for-js。
您还需要确保您的函数文件在页面加载时立即分配Office.initialize
。这不是对init函数的出站调用,它也是您正在分配init函数的属性。 Office会自动调用此方法,如果您尚未分配功能,则会导致错误。