我有一个使用 React + TypeScript 的 Outlook 插件,使用 Node.js 在本地进行调试。我正在使用 office-js-helpers 库进行身份验证和 msgraph-sdk-javascript Graph 客户端库。作为 POC,我只是试图通过通过其 id 检索当前电子邮件的详细信息来验证我是否可以成功调用 Graph。我可以成功使用 office-js-helpers Authenticator 授权应用程序,并成功检索令牌。
但是,当我使用 Graph 客户端调用 时v1/me/messages/{ID}
,我得到:
“401 InvalidAuthenticationToken:访问令牌验证失败”
我不确定这是我使用身份验证器的方式有问题,还是我的加载项或应用程序清单有问题。我的加载项将这些用于AppDomains
:
<AppDomains>
<AppDomain>https://localhost:3000</AppDomain>
<AppDomain>https://login.microsoftonline.com</AppDomain>
</AppDomains>
我正在使用https://localhost:3000
我的应用程序的重定向 URI,并启用了隐式身份验证。
如果我将 force 选项与 authenticate 方法一起使用,我也会收到此错误:
无法在“DOMWindow”上执行“postMessage”:提供的目标来源(“ https://login.microsoftonline.com ”)与收件人窗口的来源(“ https://localhost:3000 ”)不匹配。
但是,我能够检索令牌。
我究竟做错了什么?我不确定 Authenticator 的流程,何时使用authenticator.tokens.get
和authenticator.authenticate
. 对于第一次运行,我假设始终进行身份验证并且不需要使用tokens.get
,而对于第二次运行,我假设只使用tokens.ge
t,但是如果我尝试其中任何一个或始终尝试两者,它似乎不会改变无效令牌的结果。
import * as React from "react";
import { Button, ButtonType, TextField } from "office-ui-fabric-react";
import { Authenticator, Utilities, DefaultEndpoints } from "@microsoft/office-js-helpers";
import * as Graph from "@microsoft/microsoft-graph-client";
export default class GetItemOJSHelpers extends React.Component<any, any> {
constructor(props) {
super(props);
this.getEmail = this.getEmail.bind(this);
this.callGraph = this.callGraph.bind(this);
this.getItemRestId = this.getItemRestId.bind(this);
this.state = { graphResponse: "", accessToken: "" };
console.log("====GetItemOJSHelpers loaded");
}
getEmail() {
console.log("====getEmail(): Entered ");
//debugger;
// Get the access token and create a Microsoft Graph client
let authenticator = new Authenticator();
// register Microsoft (Azure AD 2.0 Converged auth) endpoint
authenticator.endpoints.registerMicrosoftAuth("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", {
redirectUrl: "https://localhost:3000/index.html",
scope: "Mail.ReadWrite User.Read User.ReadBasic.All"
});
console.log("====getEmail(): Getting token");
let authObject = authenticator.tokens.get("Microsoft");
let accessToken = authObject.access_token;
if (accessToken !== null) {
console.log(`====getEmail(): Current cached token: ${accessToken}`);
this.callGraph(accessToken);
return;
} else {
// for the default Microsoft endpoint
//If the user, rejects the grant to the application then you will receive an error in the catch function.
authenticator
.authenticate(DefaultEndpoints.Microsoft)
.then(function(token) {
/* Microsoft Token */
console.log(`====getEmail(): Authenticated; auth token: ${token.access_token}`);
accessToken = token.access_token;
})
.catch(function(error) {
//debugger;
console.log("====getEmail(): authenticate error");
Utilities.log(error);
throw new Error("Failed to login using your Office 365 Account");
});
}
console.log(`====getEmail(): Current token: ${accessToken}`);
this.callGraph(accessToken);
}
callGraph(token) {
// Get the item's REST ID
let itemId = this.getItemRestId();
console.log(`====callGraph(): itemId ${itemId}`);
const client = Graph.Client.init({
authProvider: done => {
done(null, token); //first parameter takes an error if you can't get an access token
},
debugLogging: true
});
client
.api("me/messages/" + itemId)
.version("v1.0")
.get()
.then(function(item) {
//debugger;
console.log("Email " + item.Subject + " retrieved!!!");
})
.then(function() {
console.log("====callGraph(): complete");
//debugger;
})
.catch(err => {
//debugger;
//403 Forbidden! code: "ErrorAccessDenied", message: "Access is denied. Check credentials and try again."
//Also 401 InvalidAuthenticationToken: Access token validation failure.
console.log(`====callGraph(): error! ${err.statusCode}:'${err.code}': ${err.message}`);
});
}
getItemRestId() {
if (Office.context.mailbox.diagnostics.hostName === "OutlookIOS") {
// itemId is already REST-formatted
return Office.context.mailbox.item.itemId;
} else {
// Convert to an item ID for API v2.0
return Office.context.mailbox.convertToRestId(
Office.context.mailbox.item.itemId,
Office.MailboxEnums.RestVersion.v2_0
);
}
}
render() {
return (
<div>
<Button
id="getEmailButton"
className="ms-welcome__action ms-bgColor-red"
buttonType={ButtonType.primary}
onClick={this.getEmail}
>
Call Graph
</Button>
<div>
<h3> Access Token </h3>
<TextField id="accessToken" />
</div>
<div>
<h3>Graph API Call Response</h3>
<TextField id="graphResponse" />
</div>
</div>
);
}
}