빠른 시작: 민감도 레이블 설정 및 가져오기(C++)

이 빠른 시작에서는 더 많은 MIP 파일 SDK를 사용하는 방법을 보여 줍니다. 이전 빠른 시작에 나열된 민감도 레이블 중 하나를 사용하여 파일 처리기를 사용하여 파일에 레이블을 설정/가져올 수 있습니다. 파일 처리기 클래스는 지원되는 파일 형식에 대해 레이블을 설정/가져오거나 보호하기 위한 다양한 작업을 노출합니다.

필수 조건

아직 완료하지 않은 경우 계속하기 전에 다음 필수 구성 요소를 완료해야 합니다.

  • 먼저, 시작 Visual Studio 솔루션을 구축하는 빠른 시작: 민감도 레이블 나열(C++)을 완료하여 조직의 민감도 레이블을 나열합니다. 이 “민감도 레이블 설정 및 가져오기” 빠른 시작은 이전 빠른 시작에 빌드합니다.
  • 선택 사항: MIP SDK의 파일 처리기 개념을 검토합니다.

파일 처리기 개체를 모니터링하는 관찰자 클래스 구현

애플리케이션 초기화 빠른 시작에서 구현한 관찰자(파일 프로필 및 엔진용)와 마찬가지로 이제 파일 처리기 개체에 대한 관찰자 클래스를 구현합니다.

SDK의 mip::FileHandler::Observer 클래스를 확장하여 파일 처리기 관찰자에 대한 기본 구현을 만듭니다. 관찰자는 파일 처리기 작업을 모니터링하기 위해 인스턴스화되고 나중에 사용됩니다.

  1. 이전 “빠른 시작: 민감도 레이블 나열(C++)” 문서에서 작업한 Visual Studio 솔루션을 엽니다.

  2. 프로젝트에 새 클래스를 추가하여 header/.h 및 implementation/.cpp 파일을 모두 생성합니다.

    • 솔루션 탐색기에서 프로젝트 노드를 다시 마우스 오른쪽 단추로 클릭하고 추가를 선택한 다음, 클래스를 선택합니다.
    • 클래스 추가 대화 상자에서 다음을 수행합니다.
      • 클래스 이름 필드에 "filehandler_observer"를 입력합니다. .h 파일.cpp 파일 필드는 모두 입력한 이름에 따라 자동으로 채워집니다.
      • 완료되면 확인 단추를 클릭합니다.
  3. 클래스에 대해 .h 및 .cpp 파일을 생성한 후 두 파일이 편집기 그룹 탭에서 열립니다. 이제 각 파일을 업데이트하여 새 관찰자 클래스를 구현합니다.

    • 생성된 filehandler_observer 클래스를 선택/삭제하여 "filehandler_observer.h"를 업데이트합니다. 이전 단계에서 생성된 전처리기 지시문(#pragma, #include)을 제거하지 않습니다. 그런 다음, 기존 전처리기 지시문 뒤에 다음 원본을 파일에 복사/붙여넣습니다.

      #include <memory>
      #include "mip/file/file_engine.h"
      #include "mip/file/file_handler.h"
      
      class FileHandlerObserver final : public mip::FileHandler::Observer {
      public:
         FileHandlerObserver() { }
         // Observer implementation
         void OnCreateFileHandlerSuccess(const std::shared_ptr<mip::FileHandler>& fileHandler, const std::shared_ptr<void>& context) override;
         void OnCreateFileHandlerFailure(const std::exception_ptr& error, const std::shared_ptr<void>& context) override;
         void OnCommitSuccess(bool committed, const std::shared_ptr<void>& context) override;
         void OnCommitFailure(const std::exception_ptr& error, const std::shared_ptr<void>& context) override;		
      };
      
    • 생성된 filehandler_observer 클래스 구현을 선택/삭제하여 "filehandler_observer.cpp"를 업데이트합니다. 이전 단계에서 생성된 전처리기 지시문(#pragma, #include)을 제거하지 않습니다. 그런 다음, 기존 전처리기 지시문 뒤에 다음 원본을 파일에 복사/붙여넣습니다.

      void FileHandlerObserver::OnCreateFileHandlerSuccess(const std::shared_ptr<mip::FileHandler>& fileHandler, const std::shared_ptr<void>& context) {
         auto promise = std::static_pointer_cast<std::promise<std::shared_ptr<mip::FileHandler>>>(context);
         promise->set_value(fileHandler);
      }
      
      void FileHandlerObserver::OnCreateFileHandlerFailure(const std::exception_ptr & error, const std::shared_ptr<void>& context) {
         auto promise = std::static_pointer_cast<std::promise<std::shared_ptr<mip::FileHandler>>>(context);
         promise->set_exception(error);
      }
      
      void FileHandlerObserver::OnCommitSuccess(bool committed, const std::shared_ptr<void>& context) {
         auto promise = std::static_pointer_cast<std::promise<bool>>(context);
         promise->set_value(committed);
      }
      
      void FileHandlerObserver::OnCommitFailure(const std::exception_ptr & error, const std::shared_ptr<void>& context) {
         auto promise = std::static_pointer_cast<std::promise<bool>>(context);
         promise->set_exception(error);
      }
      
  4. 선택적으로 F6(빌드 솔루션) 키를 사용하여 솔루션의 테스트 컴파일/링크를 실행하여 계속하기 전에 성공적으로 빌드할 수 있도록 합니다.

민감도 레이블을 설정하고 가져올 논리 추가

파일 엔진 개체를 사용하여 파일에 민감도 레이블을 설정하고 가져올 수 있는 논리를 추가합니다.

  1. 솔루션 탐색기를 사용하여 main() 메서드 구현을 포함하는 프로젝트에서 .cpp 파일을 엽니다. 기본값은 프로젝트 생성 중에 지정한 이름이 포함된 프로젝트와 동일한 이름입니다.

  2. 파일 상단의 해당 기존 지시문 아래에 #includeusing 지시문을 추가합니다.

    #include "filehandler_observer.h" 
    #include "mip/file/file_handler.h" 
    
    using mip::FileHandler;
    
  3. main() 본문의 끝부분을 향해 system("pause"); 아래 및 return 0; 위에(이전 빠른 시작에서 중단한 부분) 다음 코드를 삽입합니다.

    // Set up async FileHandler for input file operations
    string inputFilePath = "<input-file-path>";
    string actualFilePath = "<content-identifier>";
    std::shared_ptr<FileHandler> handler;
    try
    {
         auto handlerPromise = std::make_shared<std::promise<std::shared_ptr<FileHandler>>>();
         auto handlerFuture = handlerPromise->get_future();
         engine->CreateFileHandlerAsync(
              inputFilePath,
              actualFilePath,                       
              true, 
              std::make_shared<FileHandlerObserver>(), 
              handlerPromise);
         handler = handlerFuture.get();
    }
    catch (const std::exception& e)
    {
         cout << "An exception occurred... did you specify a valid input file path?\n\n" << e.what() << "'\n";
         system("pause");
         return 1;
    }
    
    // Set a label on input file
    try
    {
         string labelId = "<label-id>";
         cout << "\nApplying Label ID " << labelId << " to " << filePathIn << endl;
         mip::LabelingOptions labelingOptions(mip::AssignmentMethod::PRIVILEGED);
         handler->SetLabel(engine->GetLabelById(labelId), labelingOptions, new ProtectionSettings());
    }
    catch (const std::exception& e)
    {
         cout << "An exception occurred... did you specify a valid label ID?\n\n" << e.what() << "'\n";
         system("pause");
         return 1; 
    }
    
    // Commit changes, save as a different/output file
    string filePathOut = "<output-file-path>";
    try
    {
     	cout << "Committing changes" << endl;
         auto commitPromise = std::make_shared<std::promise<bool>>();
         auto commitFuture = commitPromise->get_future();
         handler->CommitAsync(filePathOut, commitPromise);
     	if (commitFuture.get()) {
     		cout << "\nLabel committed to file: " << filePathOut << endl;
     	}
     	else {
     		cout << "Failed to label: " + filePathOut << endl;
     		return 1;
     	}
    }
    catch (const std::exception& e)
    {
         cout << "An exception occurred... did you specify a valid commit file path?\n\n" << e.what() << "'\n";
         system("pause");
         return 1;
    }
    system("pause");
    
    // Set up async FileHandler for output file operations
    actualFilePath = "<content-identifier>";
    try
    {
         auto handlerPromise = std::make_shared<std::promise<std::shared_ptr<FileHandler>>>();
         auto handlerFuture = handlerPromise->get_future();
         engine->CreateFileHandlerAsync(
              filePathOut,
              actualFilePath,
              true,
              std::make_shared<FileHandlerObserver>(),
              handlerPromise);
    
         handler = handlerFuture.get();
    }
    catch (const std::exception& e)
    {
         cout << "An exception occurred... did you specify a valid output file path?\n\n" << e.what() << "'\n";
         system("pause");
         return 1;
    }
    
    // Get the label from output file
    try
    {
         cout << "\nGetting the label committed to file: " << filePathOut << endl;
         auto label = handler->GetLabel();
         cout << "Name: " + label->GetLabel()->GetName() << endl;
         cout << "Id: " + label->GetLabel()->GetId() << endl;
    }
    catch (const std::exception& e)
    {
         cout << "An exception occurred... did you specify a valid label ID?\n\n" << e.what() << "'\n";
         system("pause");
         return 1;
    }
    system("pause");
    
  4. main()의 끝부분을 향해 첫 번째 빠른 시작에서 생성된 애플리케이션 종료 블록을 찾고 처리기 줄의 주석 처리를 제거합니다.

    // Application shutdown. Null out profile and engine, call ReleaseAllResources();
    // Application may crash at shutdown if resources aren't properly released.
    profile = nullptr;
    engine = nullptr;
    handler = nullptr;
    mipContext = nullptr;
    
  5. 문자열 상수를 사용하여 다음과 같이 소스 코드의 자리 표시자 값을 바꿉니다.

    자리 표시자
    <input-file-path> 테스트 입력 파일에 대한 전체 경로(예: "c:\\Test\\Test.docx").
    <content-identifier> 콘텐츠에 대해 사람이 읽을 수 있는 식별자입니다. 예:
    • 파일의 경우 path\filename("c:\Test\Test.docx")을 고려합니다.
    • 이메일의 경우 subject:sender("RE: Audit design:user1@contoso.com")를 고려합니다.
    <label-id> 이전 빠른 시작의 콘솔 출력에서 복사한 민감도 레이블 ID(예: "f42a3342-8706-4288-bd31-ebb85995028z").
    <output-file-path> 입력 파일의 레이블이 지정된 복사본인 출력 파일의 전체 경로(예: "c:\\Test\\Test_labeled.docx").

응용 프로그램 구축 및 테스트

클라이언트 애플리케이션을 빌드하고 테스트합니다.

  1. F6(솔루션 빌드)을 사용하여 클라이언트 애플리케이션을 빌드합니다. 빌드 오류가 없는 경우 F5(디버깅 시작) 키를 사용하여 애플리케이션을 실행합니다.

  2. 프로젝트가 빌드 및 실행에 성공하면 SDK가 AcquireOAuth2Token() 메서드를 호출할 때마다 애플리케이션에서 액세스 토큰을 묻는 메시지가 표시됩니다. "민감도 레이블 나열" 빠른 시작에서 이전에 수행한 것처럼 $authority 및 $resourceUrl에 대해 제공된 값을 사용하여 매번 PowerShell 스크립트를 실행하여 토큰을 획득합니다.

    Run the PowerShell script to generate an access token using the following values, then copy/paste it below:
    
    Sensitivity labels for your organization:
    Non-Business : 87ba5c36-17cf-14793-bbc2-bd5b3a9f95cz
    Public : 83867195-f2b8-2ac2-b0b6-6bb73cb33afz
    General : f42a3342-8706-4288-bd31-ebb85995028z
    Confidential : 074e457c-5848-4542-9a6f-34a182080e7z
    Highly Confidential : f55c2dea-db0f-47cd-8520-a52e1590fb6z
    Press any key to continue . . .
    
    Applying Label ID 074e457c-5848-4542-9a6f-34a182080e7z to c:\Test\Test.docx
    Committing changes
    
    Label committed to file: c:\Test\Test_labeled.docx
    Press any key to continue . . .
    
    Getting the label committed to file: c:\Test\Test_labeled.docx
    Name: Confidential
    Id: 074e457c-5848-4542-9a6f-34a182080e7z
    Press any key to continue . . .
    

출력 파일을 열고 문서의 정보 보호 설정을 시각적으로 검사하여 레이블의 애플리케이션을 확인할 수 있습니다.

참고 항목

Office 문서에 레이블을 지정하지만 액세스 토큰을 가져온 Microsoft Entra 테넌트의 계정을 사용하여 로그인하지 않은 경우(및 민감도 레이블이 구성된 경우) 레이블이 지정된 문서를 열기 전에 로그인하라는 메시지가 표시될 수 있습니다.