代码之家  ›  专栏  ›  技术社区  ›  Eric Legault

使用Office JS助手认证器使用MSGSDK JavaScript进行令牌错误

  •  0
  • Eric Legault  · 技术社区  · 6 年前

    我有一个outlook插件,使用react+typescript,使用node.js进行本地调试。我使用Office JS帮助器库和MSCOSDK SDKJavaScript图形客户端库。作为一个poc,我只是试图通过检索当前电子邮件的id来验证我是否可以成功调用graph。我可以成功地使用office js helpers身份验证器来授权应用程序,并成功地检索令牌。

    但是,当我使用图形客户机调用 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.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>
        );
      }
    }
    
    0 回复  |  直到 6 年前