0

Dynamics 365 Web Api にアクセスできるようにする Typescript を使用して React で単語アドインを開発しようとしています。私が実際に見つけた最良の例は、こちらの MSAL 2.0 を使用してグラフ API にアクセスするサンプル Excel アドインでしたhttps://github.com/OfficeDev/PnP-OfficeAddins/tree/master/Samples/auth/Office-Add- in-Microsoft-Graph-React。サンプル コードを変更した後、Dynamics 365 API への取得要求を成功させることができれば、コードを Word アドインに移植します。

ただし、 https://saltrial.crm.dynamics.com/api/data/v9.1/に移動しようとすると 401 エラーが発生し続けます。
これをブラウザーに貼り付けるだけで応答が返されますが、追加で 401 権限がありません。また、アドインから受け取ったトークンを Bearer + token のヘッダーで postman に貼り付けると、401 無許可になります。成功したアクセストークンを取得しましたが、選択したときに

ここに画像の説明を入力

Azure AD でのセットアップをお見せします... クライアント シークレットのセットアップがありますが、アドイン コードでそれを使用していません。

ここに画像の説明を入力

ここに画像の説明を入力 ここに画像の説明を入力 ここに画像の説明を入力 ここに画像の説明を入力

マニフェスト { "id": "35c3a758-0edb-45f6-a97d-9c7180decd73", "acceptMappedClaims": null, "accessTokenAcceptedVersion": 2, "addIns": [], "allowPublicClient": true, "appId": "4f7xxxxxxxxxxxxxxxxxxxxxx310bf0" , "appRoles": [], "oauth2AllowUrlPathMatching": false, "createdDateTime": "2021-01-24T07:09:12Z", "disabledByMicrosoftStatus": null, "groupMembershipClaims": null, "identifierUris": [ "api: //localhost:3000/4fxxxxxxxxxxxxxxxxxxxxxxx" ], "informationalUrls": { "termsOfService": null, "support": null, "privacy": null, "marketing": null }, "keyCredentials": [], "knownClientApplications" : [], "logoUrl": null, "logoutUrl": null, "name": "TrySSO", "oauth2AllowIdTokenImplicitFlow": true, "oauth2AllowImplicitFlow": true, "oauth2Permissions": [ { "adminConsentDescription": "Office が同じ権限でアドインの Web API を呼び出せるようにする現在のユーザーとして。 ": "Application", "type": "User", "userConsentDescription": "Office があなたと同じ権限でアドインの Web API を呼び出せるようにします。", "userConsentDisplayName": "Office はあなたとして機能できます" , "値": "access_as_user" } ],"oauth2RequirePostResponse": false, "optionalClaims": null, "orgRestrictions": [], "parentalControlSettings": { "countriesBlockedForMinors": [], "legalAgeGroupRule": "許可" }, "passwordCredentials": [ { "customKeyIdentifier": null、"endDate": "2299-12-31T05:00:00Z"、"keyId": "570axxxxxxxxxxxxxxxxxxxxxxxxxxbcd1"、"startDate": "2021-01-28T04:11:05.086Z"、"value": null、" createdOn": "2021-01-28T04:11:06.027737Z", "hint": "mm-", "displayName": "wordaddinsecret" } ], "preAuthorizedApplications": [ { "appId": "ea5a67f6-b6f3- 4338-b240-c655ddc3cc8e", "permissionIds": [ "5b3a4e4a-e55e-45ba-820b-ea16efbe3d5f" ] }, { "appId": "d3590ed6-52b3-4102-aeff-aad2292ab01c", "permissionIds": [ "5b3a4e4a-e55e-45ba-820b-ea16efbe3d5f" ] }, { "appId": "57fb890c-0dab-4253-a5e0-7188c88b2bb4", "permissionIds": [ "5b3a4e4a-e55e-45ba-820b-ea16efbe3d5f" ] }, { "appId": "bc59ab01-8403-45c6-8796-ac3ef710b3e3e" ", "permissionIds": [ "5b3a4e4a-e55e-45ba-820b-ea16efbe3d5f" ] } ], "publisherDomain": "salnewtrial.onmicrosoft.com", "replyUrlsWithType": [ { "url": "https://localhost :3000/login/login.html", "type": "スパ" }, { "url": "https://login.microsoftonline.com/common/oauth2/nativeclient", "type": "InstalledClient" }, { "url": "https://localhost:3000/login.html", "type": "Web" } ], "requiredResourceAccess": [ { "resourceAppId": "00000007-0000-0000- c000-000000000000", "resourceAccess": [ { "id": "78ce3f0f-a1ce-49c2-8cde-64b5c0896db4", "type": "スコープ" } ] }, { "resourceAppId": "00000003-0000-0000- c000-000000000000", "resourceAccess": [ { "id": "14dad69e-099b-42c9-810b-d002981feec1", "タイプ": "スコープ" }, { "id": "7427e0e9-2fba-42fe-b0c0- 848c9e6a8182", "タイプ": "スコープ" }, { "id": "37f7f235-527c-4136-accd-4a02d197296e", "タイプ": "スコープ" }, { "id": "e1fe6dd8-ba31-4d61-89e7-88639da4683d", "type": "Scope" } ] } ], "samlMetadataUrl": null, "signInUrl": null, "signInAudience": "AzureADMyOrg", "tags": [], "tokenEncryptionKeyId": null }

私のlogin.ts内のExcelアドイン

  (() => {
  // The initialize function must be run each time a new page is loaded
  Office.initialize = () => {
    const msalInstance = new PublicClientApplication({
      auth: {
        clientId: "4f7f40ec-xxxxxxxxx-5d6b18310bf0",
        authority: "https://login.microsoftonline.com/cd77a053-xxxxxxxxxx3402c0fd62",  *This is tenant id
        redirectUri: "https://localhost:3000/login/login.html", // Must be registered as "spa" type
      },
      cache: {
        cacheLocation: "localStorage", // needed to avoid "login required" error
        storeAuthStateInCookie: true, // recommended to avoid certain IE/Edge issues
      },
    });

    // handleRedirectPromise should be invoked on every page load
    msalInstance
      .handleRedirectPromise()
      .then((response) => {
        // If response is non-null, it means page is returning from AAD with a successful response
        if (response) {
          Office.context.ui.messageParent(
            JSON.stringify({ status: "success", result: response.accessToken })
          );
        } else {
          // Otherwise, invoke login
          msalInstance.loginRedirect({
            scopes: [
              "user.read",
              "files.read.all",
              "https://saltrial.crm.dynamics.com//user_impersonation",
            ],
          });
        }
      })
      .catch((error) => {
        const errorData: string = `errorMessage: ${error.errorCode}
                                   message: ${error.errorMessage}
                                   errorCode: ${error.stack}`;
        Office.context.ui.messageParent(
          JSON.stringify({ status: "failure", result: errorData })
        );
      });
  };
})();

アドインでの API 呼び出しは次のとおりです。

    import axios from 'axios';

export const getGraphData = async (url: string, accesstoken: string) => {
    const response = await axios({
        url: url,
        method: 'get',
        headers: {'Authorization': `Bearer ${accesstoken}`,
        'OData-MaxVersion': '4.0',
        'OData-Version': '4.0',
        "Accept": "application/json",
        "Content-Type": "application/json; charset=utf-8",
       }
      });
    return response;
};

API 関数を呼び出し、スコープとダイナミクスの URL を渡すコード。アクセス トークンをコンソール ログに記録し、ヘッダー ベアラー トークンを使用して郵便配達員に入力すると、401 が表示されます。また、アドインはタスク ペインに 401 無許可を表示します....グラフ API を参照する関数の名前は無視します。ダイナミクス 365 API をヒットし、401 エラーが発生しないことを願っています。ありがとう。

getFileNames = async () => {
    this.setState({ fileFetch: "fetchInProcess" });
    getGraphData(
      // Get the `name` property of the first 3 Excel workbooks in the user's OneDrive.
      "https://saltrial.crm.dynamics.com/api/data/v9.1/WhoAmI",
      this.accessToken
    )
      .then(async (response) => {
        await writeFileNamesToWorksheet(response, this.displayError);
        this.setState({ fileFetch: "fetched", headerMessage: "Success" });
      })
      .catch((requestError) => {
        // If this runs, then the `then` method did not run, so this error must be
        // from the Axios request in getGraphData, not the Office.js in
        // writeFileNamesToWorksheet
        console.log("Access Token >>>>>>>>>>>>>>>>> ", this.accessToken);
        this.displayError(requestError);
      });
  };
4

0 に答える 0