クイック スタート: クライアント アプリケーションの初期化 (C++)

このクイックスタートでは、MIP C++ SDK が実行時に使用するクライアント初期化パターンを実装する方法について説明します。

注

MIP ファイル、ポリシー、または保護 SDK を使用するすべてのクライアント アプリケーションには、このクイック スタートで説明されている手順が必要です。 このクイック スタートではファイル SDK の使用方法を示しますが、ポリシー SDK と保護 SDK を使用するクライアントにも同じパターンが適用されます。 残りのクイック スタートは、それぞれが前のクイック スタートに基づいており、これが最初のものであるため、順次完了します。

[前提条件]

まだ行っていない場合は、次の手順を実行してください。

Visual Studio ソリューションとプロジェクトを作成する

まず、他のクイックスタートの基礎となる初期の Visual Studio ソリューションとプロジェクトを作成して構成します。

  1. Visual Studio 2022 以降を開き、[ ファイル ] メニューの [ 新規作成]、[ プロジェクト] の順に選択します。 [ 新しいプロジェクト ] ダイアログで、次の手順を実行します。

    • 左側のウィンドウの [ インストール済み] の [ その他の言語] で、[ Visual C++] を選択します。

    • 中央のウィンドウで、[Windows コンソール アプリケーション] を選択します

    • 下部のウィンドウで、プロジェクト 名、 場所、および含まれている ソリューション名 を適宜更新します。

    • 完了したら、右下にある [OK] ボタンをクリックします。

      Visual Studio でのソリューション作成

  2. MIP ファイル SDK の NuGet パッケージをプロジェクトに追加します。

    • ソリューション エクスプローラーで、プロジェクト ノード (上部またはソリューション ノードのすぐ下) を右クリックし、[NuGet パッケージの管理]を選択します。..:

    • [エディター グループ] タブ領域で [NuGet パッケージ マネージャー ] タブが開いたとき:

      • を選択し、を参照します。
      • 検索ボックスに「Microsoft.InformationProtection」と入力します。
      • "Microsoft.InformationProtection.File" パッケージを選択します。
      • [インストール] をクリックし、[ プレビューの変更 の確認] ダイアログが表示されたら [OK] をクリックします。

      Visual Studio に NuGet パッケージを追加します。

ファイル プロファイルとエンジン オブジェクトを監視するオブザーバー クラスを実装する

次に、SDK の mip::FileProfile::Observer クラスを拡張して、ファイル プロファイル オブザーバー クラスの基本的な実装を作成します。 後でオブザーバーをインスタンス化して使用して、ファイル プロファイル オブジェクトの読み込みとエンジン オブジェクトのプロファイルへの追加を監視します。

  1. プロジェクトに新しいクラスを追加すると、ヘッダー/.h ファイルと implementation/.cpp ファイルの両方が生成されます。

    • ソリューション エクスプローラーで、もう一度プロジェクト ノードを右クリックし、[追加] を選択し、[クラス] を選択します。

    • [ クラスの追加 ] ダイアログで、次の手順を実行します。

      • [ クラス名] フィールドに「profile_observer」と入力します。 入力した名前に基づいて、 .h ファイル フィールドと .cpp ファイル フィールドの両方が自動的に設定されます。
      • 完了したら、[ OK ] ボタンをクリックします。

      Visual Studio にクラスを追加する

  2. クラスの .h ファイルと.cpp ファイルを生成した後、Visual Studioエディター グループ タブで両方のファイルを開きます。 次に、新しいオブザーバー クラスを実装するように各ファイルを更新します。

    • 生成された profile_observer クラスを選択または削除して、"profile_observer.h" を更新します。 前の手順で生成されたプリプロセッサ ディレクティブ (#pragma、#include) は削除しないでください。 次に、既存のプリプロセッサ ディレクティブの後に、次のソースをコピーしてファイルに貼り付けます。

      #include <memory>
      #include "mip/file/file_profile.h"
      
      class ProfileObserver final : public mip::FileProfile::Observer {
      public:
           ProfileObserver() { }
           void OnLoadSuccess(const std::shared_ptr<mip::FileProfile>& profile, const std::shared_ptr<void>& context) override;
           void OnLoadFailure(const std::exception_ptr& error, const std::shared_ptr<void>& context) override;
           void OnAddEngineSuccess(const std::shared_ptr<mip::FileEngine>& engine, const std::shared_ptr<void>& context) override;
           void OnAddEngineFailure(const std::exception_ptr& error, const std::shared_ptr<void>& context) override;
      };
      
    • 生成された profile_observer クラス実装を選択または削除して、"profile_observer.cpp" を更新します。 前の手順で生成されたプリプロセッサ ディレクティブ (#pragma、#include) は削除しないでください。 次に、既存のプリプロセッサ ディレクティブの後に、次のソースをコピーしてファイルに貼り付けます。

      #include <future>
      
      using std::promise;
      using std::shared_ptr;
      using std::static_pointer_cast;
      using mip::FileEngine;
      using mip::FileProfile;
      
      void ProfileObserver::OnLoadSuccess(const shared_ptr<FileProfile>& profile, const shared_ptr<void>& context) {
           auto promise = static_pointer_cast<std::promise<shared_ptr<FileProfile>>>(context);
           promise->set_value(profile);
      }
      
      void ProfileObserver::OnLoadFailure(const std::exception_ptr& error, const shared_ptr<void>& context) {
           auto promise = static_pointer_cast<std::promise<shared_ptr<FileProfile>>>(context);
           promise->set_exception(error);
      }
      
      void ProfileObserver::OnAddEngineSuccess(const shared_ptr<FileEngine>& engine, const shared_ptr<void>& context) {
           auto promise = static_pointer_cast<std::promise<shared_ptr<FileEngine>>>(context);
           promise->set_value(engine);
      }
      
      void ProfileObserver::OnAddEngineFailure(const std::exception_ptr& error, const shared_ptr<void>& context) {
           auto promise = static_pointer_cast<std::promise<shared_ptr<FileEngine>>>(context);
           promise->set_exception(error);
      }
      
  3. 必要に応じて、F6 (ソリューションのビルド) を使用してソリューションのテスト コンパイル/リンクを実行し、続行する前に正常にビルドされるようにします。

認証デリゲートを実装する

MIP SDK は、認証作業をクライアント アプリケーションと共有するメカニズムを提供するクラス拡張を使用して認証を実装します。 クライアントは、適切な OAuth2 アクセス トークンを取得し、実行時に MIP SDK に提供する必要があります。

次に、SDK の mip::AuthDelegate クラスを拡張し、 mip::AuthDelegate::AcquireOAuth2Token() 純粋仮想関数をオーバーライドまたは実装することで、認証デリゲートの実装を作成します。 ファイル プロファイル オブジェクトとファイル エンジン オブジェクトは、後で認証デリゲートをインスタンス化して使用します。

このクイック スタートでは、OAuth の完全な実装は意図的に提供されません。 代わりに、 MipSDK-File-Cpp-Basic の認証パターンを使用します。

サンプルの auth.h と auth.cpp ヘルパーをコピーし、マネージド トークン プロバイダーのビルド手順に従います。 ヘルパーは、ユーザー名、クライアント ID、リソース、オーソリティ、クレームを受け入れます。 その実装は、次のデリゲートをコンパイルして実行するために必要です。

  1. 前のセクションの手順 1 で使用したのと同じ Visual Studio の "クラスの追加" 機能を使用して、別のクラスをプロジェクトに追加します。 今回は、「 クラス名 」フィールドに「auth_delegate」と入力します。

  2. 次に、新しい認証デリゲート クラスを実装するように各ファイルを更新します。

    • 生成されたすべての auth_delegate クラス コードを次のソースに置き換えて、"auth_delegate.h" を更新します。 前のステップで生成された、プリプロセッサ ディレクティブ (#pragma、#include) は削除しないでください。

      #include <string>
      #include "mip/common_types.h"
      
      class AuthDelegateImpl final : public mip::AuthDelegate {
      public:
           AuthDelegateImpl() = delete;        // Prevents default constructor
      
           AuthDelegateImpl(
             const std::string& appId)         // AppID for registered Microsoft Entra app
             : mAppId(appId) {};
      
           bool AcquireOAuth2Token(                     // Called by MIP SDK to get a token
             const mip::Identity& identity,             // Identity of the account to be authenticated, if known
             const OAuth2Challenge& challenge,          // Authority (Microsoft Entra tenant issuing token), and resource (API being accessed; "aud" claim).
             const std::shared_ptr<void>& context,      // Opaque context passed by the host application through the MIP API
             OAuth2Token& token) override;              // Token handed back to MIP SDK
      
      private:
           std::string mAppId;
      };
      
    • 生成されたすべての auth_delegate クラス実装を次のソースに置き換えて、"auth_delegate.cpp" を更新します。 前の手順で生成されたプリプロセッサ ディレクティブ (#pragma、#include) は削除しないでください。

      重要

      このクイック スタートでは、MIP SDK の初期化と使用パターンに重点を置いています。 トークン取得の実装の詳細については、MipSDK-File-Cpp-Basic の MSAL.NET ベースの認証コードを使用します。

      #include <iostream>
      #include <stdexcept>
      #include "auth.h"
      
      using std::string;
      
      bool AuthDelegateImpl::AcquireOAuth2Token(const mip::Identity& identity, const OAuth2Challenge& challenge, const std::shared_ptr<void>& context, OAuth2Token& token) 
      {
        (void)context;
        try {
          string accessToken = sample::auth::AcquireToken(
            identity.GetEmail(),
            mAppId,
            challenge.GetResource(),
            challenge.GetAuthority(),
            challenge.GetClaims());
      
          if (accessToken.empty()) {
            throw std::runtime_error("Token acquisition returned an empty token.");
          }
      
          token.SetAccessToken(accessToken);
          return true;
        }
        catch (const std::exception& error) {
          std::cerr << "Authentication failed: " << error.what() << std::endl;
          return false;
        }
      }
      
  3. 必要に応じて、F6 (ソリューションのビルド) を使用してソリューションのテスト コンパイル/リンクを実行し、続行する前に正常にビルドされるようにします。

次に、SDK の mip::ConsentDelegate クラスを拡張し、 mip::AuthDelegate::GetUserConsent() 純粋仮想関数をオーバーライドまたは実装することで、同意デリゲートの実装を作成します。 ファイル プロファイル オブジェクトとファイル エンジン オブジェクトは、後で同意デリゲートをインスタンス化して使用します。

  1. 前に使用したのと同じ Visual Studio の "クラスの追加" 機能を使用して、別のクラスをプロジェクトに追加します。 今回は、「 クラス名 」フィールドに「consent_delegate」と入力します。

  2. 次に、新しい同意デリゲート クラスを実装するように各ファイルを更新します。

    • 生成されたすべての consent_delegate クラス コードを次のソースに置き換えて、"consent_delegate.h" を更新します。 前の手順で生成されたプリプロセッサ ディレクティブ (#pragma、#include) は削除しないでください。

      #include "mip/common_types.h"
      #include <string>
      
      class ConsentDelegateImpl final : public mip::ConsentDelegate {
      public:
           ConsentDelegateImpl() = default;
           virtual mip::Consent GetUserConsent(const std::string& url) override;
      };
      
    • 生成されたすべての consent_delegate クラス実装を次のソースに置き換えて、"consent_delegate.cpp" を更新します。 前のステップで生成された、プリプロセッサ ディレクティブ (#pragma、#include) は削除しないでください。

      #include <iostream>
      using mip::Consent;
      using std::string;
      
      Consent ConsentDelegateImpl::GetUserConsent(const string& url) 
      {
           // Accept the consent to connect to the url
           std::cout << "SDK will connect to: " << url << std::endl;
           return Consent::AcceptAlways;
      }
      
  3. 必要に応じて、F6 (ソリューションのビルド) を使用してソリューションのテスト コンパイル/リンクを実行し、続行する前に正常にビルドされるようにします。

ファイル プロファイルとエンジンを構築する

前述のように、MIP API を使用する SDK クライアントにはプロファイル オブジェクトとエンジン オブジェクトが必要です。 プロファイルとエンジン オブジェクトをインスタンス化するコードを追加して、このクイックスタートのコーディング部分を完了します。

  1. ソリューション エクスプローラーで、main() メソッドの実装を含む.cpp ファイルをプロジェクトで開きます。 既定の名前は、それが含まれるプロジェクトと同じであり、プロジェクトの作成時に指定したものです。

  2. 生成された main()の実装を削除します。 プロジェクトの作成時にVisual Studioによって生成されたプリプロセッサ ディレクティブ (#pragma、#include) は削除しないでください。 プリプロセッサ ディレクティブの後に次のコードを追加します。

#include "mip/mip_context.h"  
#include "auth_delegate.h"
#include "consent_delegate.h"
#include "profile_observer.h"

using std::promise;
using std::future;
using std::make_shared;
using std::shared_ptr;
using std::string;
using std::cout;
using mip::ApplicationInfo;
using mip::FileProfile;
using mip::FileEngine;

int main()
{
  // Construct/initialize objects required by the application's profile object
  // ApplicationInfo object (App ID, name, version)
  ApplicationInfo appInfo{"<application-id>",      
                          "<application-name>",
                          "<application-version>"};

  // Create MipConfiguration object.
  std::shared_ptr<mip::MipConfiguration> mipConfiguration = std::make_shared<mip::MipConfiguration>(appInfo,
                                                                                                    "mip_data",
                                                                                                    mip::LogLevel::Trace,
                                                                                                    false,
                                                                                                    mip::CacheStorageType::OnDisk);


  std::shared_ptr<mip::MipContext> mMipContext = mip::MipContext::Create(mipConfiguration);

  auto profileObserver = make_shared<ProfileObserver>();                     // Observer object
  auto authDelegateImpl = make_shared<AuthDelegateImpl>("<application-id>"); // Authentication delegate object (App ID)                 
  auto consentDelegateImpl = make_shared<ConsentDelegateImpl>();             // Consent delegate object

  // Construct/initialize profile object
  FileProfile::Settings profileSettings(
                                mMipContext,
                                mip::CacheStorageType::OnDisk,
                                consentDelegateImpl,
                                profileObserver);

  // Set up promise/future connection for async profile operations; load profile asynchronously
  auto profilePromise = make_shared<promise<shared_ptr<FileProfile>>>();
  auto profileFuture = profilePromise->get_future();

  try
	  { 
		  mip::FileProfile::LoadAsync(profileSettings, profilePromise);
  }
	  catch (const std::exception& e)
	  {
		  cout << "An exception occurred... are the Settings and ApplicationInfo objects populated correctly?\n\n" << e.what() << "'\n";
			
		  system("pause");
		  return 1;
	  }
	  auto profile = profileFuture.get();

  // Construct/initialize engine object
  FileEngine::Settings engineSettings(
                                  mip::Identity("<engine-account>"), // Engine identity (account used for authentication)
                                  authDelegateImpl,		       // Token acquisition implementation
				    "<engine-state>",                  // User-defined engine state
                                  "en-US");                          // Locale (default = en-US)
                                  
  // Set the engineId for caching. 
  engineSettings.SetEngineId("<engine-account>");
  // Set up promise/future connection for async engine operations; add engine to profile asynchronously
  auto enginePromise = make_shared<promise<shared_ptr<FileEngine>>>();
  auto engineFuture = enginePromise->get_future();
  profile->AddEngineAsync(engineSettings, enginePromise);
  std::shared_ptr<FileEngine> engine; 
  try
  {
    engine = engineFuture.get();
  }
  catch (const std::exception& e)
  {
    cout << "An exception occurred... is the access token incorrect/expired?\n\n" << e.what() << "'\n";
     
    system("pause");
    return 1;
  }

  // Application shutdown. Null out profile and engine, call ReleaseAllResources();
  // Application may crash at shutdown if resources aren't properly released.
  // handler = nullptr; // This will be used in later quick starts.
  engine = nullptr;
  profile = nullptr;   
  mMipContext->ShutDown();
  mMipContext = nullptr;

  return 0;
  }
  1. 文字列定数を使用して、貼り付けたソース コード内のすべてのプレースホルダー値を置き換えます。

    プレースホルダー 価値 例
    <application-id> 「MIP SDK のセットアップと構成」の記事の手順 2 で登録されたアプリケーションに割り当てられたMicrosoft Entra アプリケーション ID (GUID)。 2 つのインスタンスを置き換えます。 "00001111-aaaa-2222-bbbb-3333cccc4444"
    <application-name> アプリケーションのユーザー定義のフレンドリ名。 有効な ASCII 文字 (';' を除く) を含める必要があり、Microsoft Entra 登録で使用したアプリケーション名と一致するのが理想的です。 "AppInitialization"
    <application-version> アプリケーションのユーザー定義バージョン情報。 有効な ASCII 文字 (';' を除く) を含める必要があります。 "1.1.0.0"
    <engine-account> エンジンの ID に使用されるアカウント。 トークンの取得中にユーザー アカウントで認証を行う場合は、この値と一致する必要があります。 "user1@tenant.onmicrosoft.com"
    <engine-state> エンジンに関連付けるユーザー定義の状態。 "My App State"
  2. アプリケーションの最終的なビルドを実行し、エラーを解決します。 コードが正常にビルドされます。 エンド ツー エンドで実行する前に、認証デリゲートがサンプル ベースのトークン取得フローに接続されていることを確認します。

次のステップ

初期化コードが完了したら、MIP ファイル SDK の使用を開始する次のクイック スタートの準備ができました。