Notitie
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen u aan te melden of de directory te wijzigen.
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen de mappen te wijzigen.
In dit voorbeeld ziet u hoe u een extern Python-script aanroept om een OAuth2-token te verkrijgen. Een geldig OAuth2-toegangstoken is vereist door de implementatie van de verificatiedelegatie.
Vereiste voorwaarden
Het voorbeeld uitvoeren:
- Installeer Python 3.10 of hoger.
- Implementeer utils.h/cpp in uw project.
- Auth.py moet worden toegevoegd aan uw project en in dezelfde map staan als de binaire bestanden in de build.
- Voltooi de installatie en configuratie van de MICROSOFT Information Protection -SDK (MIP). Naast andere taken registreert u uw clienttoepassing in uw Microsoft Entra-tenant. Microsoft Entra-id biedt een toepassings-id, ook wel client-id genoemd, die wordt gebruikt in uw tokenovernamelogica.
Deze code is niet bedoeld voor productiegebruik. Het kan alleen worden gebruikt voor het ontwikkelen en begrijpen van verificatieconcepten. Het voorbeeld is platformoverschrijdend.
voorbeeld::auth::AcquireToken()
In het voorbeeld van eenvoudige verificatie hebben we een eenvoudige AcquireToken() functie gedemonstreerd die geen parameters heeft gebruikt en een in code vastgelegde tokenwaarde heeft geretourneerd. In dit voorbeeld overbelasten we AcquireToken() om verificatieparameters te accepteren en een extern Python-script aan te roepen om het token te retourneren.
auth.h
In auth.h wordt AcquireToken() overbelast, en de bijbehorende functie en bijgewerkte parameters zijn als volgt:
//auth.h
#include <string>
namespace sample {
namespace auth {
std::string AcquireToken(
const std::string& userName, //A string value containing the user's UPN.
const std::string& password, //The user's password in plaintext
const std::string& clientId, //The Azure AD client ID (also known as Application ID) of your application.
const std::string& resource, //The resource URL for which an OAuth2 token is required. Provided by challenge object.
const std::string& authority); //The authentication authority endpoint. Provided by challenge object.
}
}
De eerste drie parameters worden geleverd door gebruikersinvoer of in code vastgelegd in uw toepassing. De laatste twee parameters worden door de SDK aan de gemachtigde voor verificatie verstrekt.
auth.cpp
In auth.cpp voegen we de overbelaste functiedefinitie toe en definiƫren we vervolgens de code die nodig is om het Python-script aan te roepen. De functie accepteert alle opgegeven parameters en geeft deze door aan het Python-script. Het script wordt uitgevoerd en retourneert het token in tekenreeksindeling.
#include "auth.h"
#include "utils.h"
#include <fstream>
#include <functional>
#include <memory>
#include <string>
using std::string;
using std::runtime_error;
namespace sample {
namespace auth {
//This function implements token acquisition in the application by calling an external Python script.
//The Python script requires username, password, clientId, resource, and authority.
//Username, Password, and ClientId are provided by the user/developer
//Resource and Authority are provided as part of the OAuth2Challenge object that is passed in by the SDK to the AuthDelegate.
string AcquireToken(
const string& userName,
const string& password,
const string& clientId,
const string& resource,
const string& authority) {
string cmd = "python";
if (sample::FileExists("auth.py"))
cmd += " auth.py -u ";
else
throw runtime_error("Unable to find auth script.");
cmd += userName;
cmd += " -p ";
cmd += password;
cmd += " -a ";
cmd += authority;
cmd += " -r ";
cmd += resource;
cmd += " -c ";
// Replace <application-id> with the Application ID provided during your Azure AD application registration.
cmd += (!clientId.empty() ? clientId : "<application-id>");
string result = sample::Execute(cmd.c_str());
if (result.empty())
throw runtime_error("Failed to acquire token. Ensure Python is installed correctly.");
return result;
}
}
}
Python Script
Met dit script worden verificatietokens rechtstreeks verkregen via Microsoft Authentication Library (MSAL) voor Python. Deze code is alleen opgenomen als een middel om verificatietokens te verkrijgen voor gebruik door de voorbeeld-apps en is niet bedoeld voor gebruik in productie. Het script werkt alleen voor tenants die ondersteuning bieden voor gewone oude verificatie van gebruikersnaam en wachtwoord. Verificatie op basis van MFA of certificaten wordt niet ondersteund via dit script.
Opmerking
Voordat u dit voorbeeld uitvoert, moet u MSAL voor Python installeren door een van de volgende opdrachten uit te voeren:
pip install msal
pip3 install msal
import getopt
import sys
import json
import re
from msal import PublicClientApplication
def printUsage():
print('auth.py -u <username> -p <password> -a <authority> -r <resource> -c <clientId>')
def main(argv):
try:
options, args = getopt.getopt(argv, 'hu:p:a:r:c:')
except getopt.GetoptError:
printUsage()
sys.exit(-1)
username = ''
password = ''
authority = ''
resource = ''
clientId = ''
for option, arg in options:
if option == '-h':
printUsage()
sys.exit()
elif option == '-u':
username = arg
elif option == '-p':
password = arg
elif option == '-a':
authority = arg
elif option == '-r':
resource = arg
elif option == '-c':
clientId = arg
if username == '' or password == '' or authority == '' or resource == '' or clientId == '':
printUsage()
sys.exit(-1)
# ONLY FOR DEMO PURPOSES AND MSAL FOR PYTHON
# This shouldn't be required when using proper auth flows in production.
if authority.find('common') > 1:
authority = authority.split('/common')[0] + "/organizations"
app = PublicClientApplication(client_id=clientId, authority=authority)
result = None
if resource.endswith('/'):
resource += ".default"
else:
resource += "/.default"
# *DO NOT* use username/password authentication in production system.
# Instead, consider auth code flow and using a browser to fetch the token.
result = app.acquire_token_by_username_password(username=username, password=password, scopes=[resource])
print(result['access_token'])
if __name__ == '__main__':
main(sys.argv[1:])
AcquireOAuth2Token bijwerken
Werk ten slotte de AcquireOAuth2Token functie bij in AuthDelegateImpl om de overbeladen AcquireToken functie aan te roepen. De bron- en instantie-URL's worden verkregen door te lezen challenge.GetResource() en challenge.GetAuthority(). De OAuth2Challenge wordt aan de auth afgevaardigde doorgegeven wanneer de engine wordt toegevoegd. Dit werk wordt uitgevoerd door de SDK en vereist geen extra werk aan het deel van de ontwikkelaar.
bool AuthDelegateImpl::AcquireOAuth2Token(
const mip::Identity& /*identity*/,
const OAuth2Challenge& challenge,
OAuth2Token& token) {
//call our AcquireToken function, passing in username, password, clientId, and getting the resource/authority from the OAuth2Challenge object
string accessToken = sample::auth::AcquireToken(mUserName, mPassword, mClientId, challenge.GetResource(), challenge.GetAuthority());
token.SetAccessToken(accessToken);
return true;
}
Wanneer engine is toegevoegd, roept de SDK de functie AcquireOAuth2Token aan, waarbij de uitdaging wordt doorgegeven, het Python-script wordt uitgevoerd, en vervolgens een token wordt ontvangen, dat daarna aan de service wordt gepresenteerd.