Guida introduttiva: Elencare i modelli di protezione (C++)Quickstart: List Protection Templates (C++)
Questo Avvio rapido illustra come usare l'API Protezione di MIP per i modelli di protezione disponibili per l'utente.This Quickstart shows you how to use the MIP Protection API, to protection templates available to the user.
PrerequisitiPrerequisites
Se non è già stato fatto, completare i prerequisiti seguenti prima di continuare:If you haven't already, be sure to complete the following prerequisites before continuing:
- In primo luogo completare l'Avvio rapido: Inizializzazione delle applicazioni client - API Protezione (C++) che compila una soluzione Visual Studio iniziale.Complete Quickstart - Client application initialization - Protection API (C++) first, which builds a starter Visual Studio solution. L'Avvio rapido "Elencare i modelli di protezione" si basa sull'Avvio rapido precedente per la creazione corretta della soluzione iniziale.This "List protection templates" Quickstart relies on the previous one, for proper creation of the starter solution.
- Facoltativamente: Esaminare i concetti in Modelli RMS.Optionally: Review RMS Templates concepts.
Aggiungere la logica per elencare i modelli di protezioneAdd logic to list the protection templates
Aggiungere la logica per elencare i modelli di protezione disponibili per un utente, usando l'oggetto motore Protezione.Add logic to list protection templates available to a user, using the Protection engine object.
Aprire la soluzione di Visual Studio creata nell'articolo precedente "Avvio rapido: Inizializzazione delle applicazioni client - API Protezione (C++).Open the Visual Studio solution you created in the previous "Quickstart - Client application initialization - Protection API (C++)" article.
Usare Esplora soluzioni per aprire il file con estensione cpp nel progetto che contiene l'implementazione del metodo
main()
.Using Solution Explorer, open the .cpp file in your project that contains the implementation of themain()
method. Per impostazione predefinita il file ha lo stesso nome del progetto che lo contiene, specificato durante la creazione del progetto.It defaults to the same name as the project containing it, which you specified during project creation.Aggiungere la direttiva
using
seguente dopousing mip::ProtectionEngine;
, vicino all'inizio del file:Add the followingusing
directive afterusing mip::ProtectionEngine;
, near the top of the file:using std::endl;
Verso la fine del corpo
main()
, dopo la parentesi graffa di chiusura}
dell'ultimo bloccocatch
e prima direturn 0;
(il punto in cui è stata interrotto l'Avvio rapido precedente), inserire il codice seguente:Toward the end of themain()
body, below the closing brace}
of the lastcatch
block and abovereturn 0;
(where you left off in the previous Quickstart), insert the following code:// List protection templates const shared_ptr<ProtectionEngineObserver> engineObserver = std::make_shared<ProtectionEngineObserver>(); // Create a context to pass to 'ProtectionEngine::GetTemplateListAsync'. That context will be forwarded to the // corresponding ProtectionEngine::Observer methods. In this case, we use promises/futures as a simple way to detect // the async operation completes synchronously. auto loadPromise = std::make_shared<std::promise<vector<shared_ptr<mip::TemplateDescriptor>>>>(); std::future<vector<shared_ptr<mip::TemplateDescriptor>>> loadFuture = loadPromise->get_future(); engine->GetTemplatesAsync(engineObserver, loadPromise); auto templates = loadFuture.get(); cout << "**_ Template List: " << endl; for (const auto& protectionTemplate : templates) { cout << "Name: " << protectionTemplate->GetName() << " : " << protectionTemplate->GetId() << endl; }
Creare uno script di PowerShell per generare i token di accessoCreate a PowerShell script to generate access tokens
Usare lo script PowerShell seguente per generare i token di accesso, richiesti dal SDK nell'implementazione AuthDelegateImpl::AcquireOAuth2Token
.Use the following PowerShell script to generate access tokens, which are requested by the SDK in your AuthDelegateImpl::AcquireOAuth2Token
implementation. Lo script usa il cmdlet Get-ADALToken
dal modulo ADAL.PS installato in precedenza, in "Installazione e configurazione di MIP SDK".The script uses the Get-ADALToken
cmdlet from the ADAL.PS module you installed earlier, in "MIP SDK Setup and configuration".
Creare un file di script di PowerShell (con estensione ps1) e copiare e incollare lo script seguente nel file:Create a PowerShell Script file (.ps1 extension), and copy/paste the following script into the file:
- I valori
$authority
e$resourceUrl
vengono aggiornati più avanti, nella sezione seguente.$authority
and$resourceUrl
are updated later, in the following section. - Aggiornare
$appId
e$redirectUri
in modo che corrispondano ai valori specificati nella registrazione dell'app in Azure AD.Update$appId
and$redirectUri
, to match the values you specified in your Azure AD app registration.
$authority = '<authority-url>' # Specified when SDK calls AcquireOAuth2Token() $resourceUrl = '<resource-url>' # Specified when SDK calls AcquireOAuth2Token() $appId = '<app-ID>' # App ID of the Azure AD app registration $redirectUri = '<redirect-uri>' # Redirect URI of the Azure AD app registration $response = Get-ADALToken -Resource $resourceUrl -ClientId $appId -RedirectUri $redirectUri -Authority $authority -PromptBehavior:RefreshSession $response.AccessToken | clip # Copy the access token text to the clipboard
- I valori
Salvare il file di script per poterlo eseguire in seguito, quando richiesto dall'applicazione client.Save the script file so you can run it later, when requested by your client application.
Compilare e testare l'applicazioneBuild and test the application
Infine, compilare e testare l'applicazione client.Finally, build and test your client application.
Usare CTRL+MAIUSC+B (*Compila soluzione ) per compilare l'applicazione client. Se non si registrano errori di compilazione, usare F5 ( Avvia debug**) per eseguire l'applicazione.Use Ctrl+Shift+b (*Build Solution ) to build your client application. If you have no build errors, use F5 ( Start debugging**) to run your application.
Se il progetto viene compilato ed eseguito correttamente, l'applicazione richiede un token di accesso ogni volta che il SDK chiama il metodo
AcquireOAuth2Token()
.If your project builds and runs successfully, the application prompts for an access token, each time the SDK calls yourAcquireOAuth2Token()
method. È possibile riutilizzare un token generato in precedenza, se viene richiesto più volte e i valori necessari sono uguali:You can reuse a previously generated token, if prompted multiple times and the requested values are the same:Per generare un token di accesso per il prompt tornare allo script di PowerShell e:To generate an access token for the prompt, go back to your PowerShell script and:
Aggiornare le variabili
$authority
e$resourceUrl
.Update the$authority
and$resourceUrl
variables. Devono corrispondere ai valori specificati nell'output della console nel passaggio 2.They must match the values that are specified in the console output in step #2.Eseguire lo script di PowerShell.Run the PowerShell script. Il cmdlet
Get-ADALToken
attiva una richiesta di autenticazione di Azure AD simile all'esempio seguente.TheGet-ADALToken
cmdlet triggers an Azure AD authentication prompt, similar to the example below. Specificare lo stesso account specificato nell'output della console nel passaggio 2.Specify the same account provided in the console output in step #2. Dopo l'accesso, il token di accesso verrà inserito negli Appunti.After successful sign-in, the access token will be placed on the clipboard.Potrebbe anche essere necessario dare il consenso, per permettere all'applicazione di accedere alle API MIP mentre viene eseguita con l'account di accesso.You may also need to give consent, to allow the application to access the MIP APIs, while running under the sign-in account. Ciò si verifica quando non è già stato dato il consenso per la registrazione dell'applicazione in Azure AD (come descritto in "Installazione e configurazione di MIP SDK") o si accede con un account da un tenant diverso da quello in cui è registrata l'applicazione.This happens when the Azure AD application registration isn't pre-consented (as outlined in "MIP SDK setup and configuration"), or you're signing in with an account from a different tenant (other than the one where your application is registered). È sufficiente fare clic su Accetta per registrare il consenso.Simply click Accept to record your consent.
Dopo aver incollato il token di accesso nella richiesta del passaggio 2, l'output della console indica i modelli di protezione, in modo simile all'esempio seguente:After pasting the access token into the prompt from step #2, your console output should show the protection templates , similar to the following example:
**_ Template List: Name: Confidential \ All Employees : a74f5027-f3e3-4c55-abcd-74c2ee41b607 Name: Highly Confidential \ All Employees : bb7ed207-046a-4caf-9826-647cff56b990 Name: Confidential : 174bc02a-6e22-4cf2-9309-cb3d47142b05 Name: Contoso Employees Only : 667466bf-a01b-4b0a-8bbf-a79a3d96f720 C:\MIP Sample Apps\ProtectionQS\Debug\ProtectionQS.exe (process 8252) exited with code 0. To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops. Press any key to continue . . .
Nota
Copiare e salvare l'ID di uno o più dei modelli di protezione (ad esempio
f42a3342-8706-4288-bd31-ebb85995028z
), perché verranno usati nell'Avvio rapido successivo.Copy and save the ID of one or more of the protection templates (for example,f42a3342-8706-4288-bd31-ebb85995028z
), as you will use it in the next Quickstart.
Risoluzione dei problemiTroubleshooting
Problemi durante l'esecuzione dell'applicazione C++Problems during execution of C++ application
RiepilogoSummary | Messaggio di erroreError message | SoluzioneSolution |
---|---|---|
Token di accesso non validoBad access token | _An exception occurred... is the access token incorrect/expired?_An exception occurred... is the access token incorrect/expired? Failed API call: profile_add_engine_async Failed with: [class mip::PolicySyncException] Failed acquiring policy, Request failed with http status code: 401, x-ms-diagnostics: [2000001;reason="OAuth token submitted with the request cannot be parsed.";error_category="invalid_token"], correlationId:[35bc0023-3727-4eff-8062-000006d5d672]'Failed API call: profile_add_engine_async Failed with: [class mip::PolicySyncException] Failed acquiring policy, Request failed with http status code: 401, x-ms-diagnostics: [2000001;reason="OAuth token submitted with the request cannot be parsed.";error_category="invalid_token"], correlationId:[35bc0023-3727-4eff-8062-000006d5d672]' C:\VSProjects\MipDev\Quickstarts\AppInitialization\x64\Debug\AppInitialization.exe (process 29924) exited with code 0.C:\VSProjects\MipDev\Quickstarts\AppInitialization\x64\Debug\AppInitialization.exe (process 29924) exited with code 0. Press any key to close this window .Press any key to close this window . .. .*.* |
Se il progetto viene compilato correttamente, ma viene visualizzato un output simile a quello riportato a sinistra, è probabile che il token nel metodo AcquireOAuth2Token() sia non valido o scaduto.If your project builds successfully, but you see output similar to the left, you likely have an invalid or expired token in your AcquireOAuth2Token() method. Tornare a Creare uno script di PowerShell per generare i token di accesso e rigenerare il token di accesso, aggiornare di nuovo AcquireOAuth2Token() e ricompilare o eseguire di nuovo il test.Go back to Create a PowerShell script to generate access tokens and regenerate the access token, update AcquireOAuth2Token() again, and rebuild/retest. È anche possibile esaminare e verificare il token e le relative attestazioni usando l'applicazione Web a pagina singola jwt.ms.You can also examine and verify the token and its claims, using the jwt.ms single-page web application. |
Passaggi successiviNext Steps
Ora che si è appreso come elencare i modelli di protezione disponibili per un utente autenticato, provare l'Avvio rapido successivo:Now that you've learned how to list the protection templates available to an authenticated user, try the next quickstart:
[Crittografare e decrittografare il testoEncrypt and Decrypt text](quick-protection-encrypt-decrypt text-cpp.md)