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

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

사전 요구 사항

아직 완료하지 않은 경우 계속하기 전에 다음 필수 조건을 완료해야 합니다.

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

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

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

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

  2. 헤더/.h 및 구현/.cpp 파일을 모두 생성하는 새 클래스를 프로젝트에 추가합니다.

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

    • 생성된 클래스를 선택/삭제하여 "filehandler_observer.h"를 filehandler_observer 업데이트합니다. 이전 단계(#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.cpp"를 filehandler_observer 업데이트합니다. 이전 단계(#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()의 끝 부분에서 첫 번째 Quick Start에서 만든 애플리케이션 종료 블록을 찾아서 처리기 줄의 주석 처리를 해제하세요.

    // 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. 문자열 상수로 소스 코드의 자리 표시자 값을 다음과 같이 바꿉니다.

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

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

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

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

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

    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 테넌트의 계정을 사용하여 로그인하지 않은 경우(및 민감도 레이블이 구성된 경우) 레이블이 지정된 문서를 열기 전에 로그인하라는 메시지가 표시될 수 있습니다.