Een toegangstoken verkrijgen (Python)

In dit voorbeeld ziet u hoe u een extern Python script aanroept om een OAuth 2.0-token te verkrijgen. Voor de implementatie van de verificatiedelegatie is een geldig OAuth 2.0-toegangstoken vereist.

Vereiste voorwaarden

Het voorbeeld uitvoeren:

  • Installeer Python 3.10 of hoger.
  • Implementeer utils.h/cpp in uw project.
  • Voeg auth.py toe aan uw project, in dezelfde map als de binaire bestanden tijdens 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, voor uw tokenverwervingslogica.

Deze code is niet bedoeld voor productiegebruik. Gebruik deze alleen voor ontwikkeling en om inzicht te hebben in verificatieconcepten. Het voorbeeld is platformoverschrijdend.

voorbeeld::auth::AcquireToken()

In het voorbeeld van eenvoudige verificatie wordt een eenvoudige AcquireToken() functie gedemonstreerd die geen parameters gebruikt en een in code vastgelegde tokenwaarde retourneert. In dit voorbeeld wordt AcquireToken() overbelast zodat het authenticatieparameters accepteert en een extern Python-script aanroept om het token terug te geven.

auth.h

In auth.h is AcquireToken() overbelast. De overbelaste 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.
    }
}

Gebruikersinvoer of uw toepassing biedt de eerste drie parameters. De SDK biedt de laatste twee parameters aan de gemachtigde voor verificatie.

auth.cpp

Het bestand auth.cpp voegt de overbelaste functiedefinitie toe en definieert vervolgens de code die het Python script aanroept. 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-scripttaal

Met dit script worden verificatietokens rechtstreeks verkregen met behulp van Microsoft Authentication Library (MSAL) voor Python. Deze code is alleen opgenomen 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 verificatie van gebruikersnaam en wachtwoord. Het script biedt geen ondersteuning voor meervoudige verificatie (MFA) of verificatie op basis van certificaten.

Opmerking

Voordat u dit voorbeeld uitvoert, installeert u MSAL voor Python 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. Lees challenge.GetResource() en challenge.GetAuthority() om de resource- en authority-URL's op te halen. De SDK geeft de OAuth2Challenge door aan de auth-delegate wanneer deze de engine toevoegt. Dit SDK-gedrag vereist geen extra werk 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 de SDK de engine toevoegt, roept deze de functie AcquireOAuth2Token aan. De functie geeft de challenge door, voert vervolgens het Python-script uit, ontvangt een token en biedt het token aan de service aan.