我创建了一个 ASP.NET MVC Web API,它托管在 azure 中。它有一个 ClientID,客户端在调用其操作方法时需要对其进行身份验证。
现在我已经创建了一个 Outlook Web 插件,并将我的插件添加到约会功能区中。 用户登录 https://outlook.office.com/ 并获得身份验证。 然后他们就可以访问约会功能区中的加载项。 当用户单击加载项图标时,加载项面板将加载到窗口右侧。
在我的加载项中,我需要填写一些下拉列表等,因此我需要从 Web API 加载数据。
首先我需要对用户进行身份验证。我读过一些文章,他们建议使用 msal.js 库。在我的加载项中,我有这部分尝试验证用户身份:
Office.onReady(function (info) {
$(document).ready(function () {
// The document is ready
GetAccessToken();
});
});
function GetAccessToken() {
//************** acquireTokenSilent
console.log('configuring msal...');
var msalConfig = {
auth: {
clientId: <web pi client it>,
authority: <my authority>,
redirectUri: <configured redirect uri on azure for the web api app reg.>
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: false
}
};
var msalInstance = new msal.PublicClientApplication(msalConfig);
console.log('msal configured');
msalInstance.acquireTokenPopup({
scopes: ["User.Read"]
})
.then(response => {
// Handle token acquisition
window.close(); // Close the popup window
// Acquire token interactive success
// Call API with token
console.log('token acquired');
accessToken = response.accessToken;
console.log('access token: ' + accessToken);
})
.catch(error => {
// Acquire token interactive failure
console.log('error acquiring token: ' + error);
});
}
运行代码时,弹出窗口会显示并对用户进行身份验证。但随后在弹出窗口中它显示了 Web api 索引页面,而不是关闭,以便我可以检索访问令牌。
我希望关闭弹出窗口,以便我可以检索访问令牌,然后将其添加到 API 调用的标头中。
我尝试使用 window.close() 手动关闭弹出窗口,但这不起作用。
如何让弹出窗口自动关闭?
let dialog;
function login() {
let a = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=Add your client id here without any space &response_type=token&redirect_uri= your redirect_uri &scope=user.read%20mail.readwrite%20mail.send&response_mode=fragment&state=12345&nonce=678910";
//let a = "https://localhost:44397/Redirect.html";
// mailboxItem.body.getAsync("html", { asyncContext: event }, checkBodyOnlyOnSendCallBack);
// Declare dialog as global for use in later functions.
Office.context.ui.displayDialogAsync(a, { height: 30, width: 20 },
function (asyncResult) {
dialog = asyncResult.value;
dialog.addEventHandler(Office.EventType.DialogMessageReceived, processMessage);
}
);
}
function processMessage(arg) {
dialog.close();
let messageFromDialog = JSON.parse(arg.message);
console.log("accessToken", messageFromDialog)
// window.localStorage.setItem("accessToken", messageFromDialog)
}
将此代码添加到您的 Redirect.html 文件中
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>
<script>
var address_Link = window.location.href;
console.log(address_Link)
var address_arr = address_Link.split("=");
var address_Token = address_arr[1];
var Id_Token = address_Token.split("&");
var access_token = Id_Token[0];
console.log(Id_Token)
Office.onReady(function (appInfo) {
Office.context.ui.messageParent(JSON.stringify(access_token));
</script>
我在网址中添加了您的客户端 ID 和您的redirect_uri。 登录成功后,您将在 js 中收到访问令牌。 希望这对你有帮助,我尽力向你解释。