共用方式為


取得存取權杖 (Python)

此範例示範如何呼叫外部 Python 腳本以取得 OAuth2 令牌。 驗證委派的實作需要有效的 OAuth2 存取令牌。

必要條件

若要執行範例:

  • 安裝 Python 3.10 或更新版。
  • 在您的項目中實作 utils.h/cpp。
  • Auth.py 應該新增至您的專案,並存在於與建置中的二進位檔相同的目錄中。
  • 完成 Microsoft 資訊保護 (MIP) SDK 設定和設定。 在其他工作中,您會在 Microsoft Entra 租用戶中註冊用戶端應用程式。 Microsoft Entra ID 提供應用程式識別碼,也稱為用戶端標識碼,用於令牌擷取邏輯中。

此程式代碼不適用於生產環境。 它只能用於開發和瞭解驗證概念。 此範例為跨平臺。

sample::auth::AcquireToken()

在簡單驗證範例中,我們示範了一 AcquireToken() 個簡單的函式,不採取任何參數,並傳回硬式編碼的令牌值。 在此範例中,我們會多載 AcquireToken() 以接受驗證參數,並呼叫外部 Python 腳本以傳回令牌。

auth.h

在 auth.h 中, AcquireToken() 會多載,且多載函式和更新的參數如下所示:

//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.
    }
}

前三個參數是由使用者輸入或硬式編碼提供給您的應用程式所提供。 最後兩個參數是由 SDK 提供給驗證委派。

auth.cpp

在auth.cpp中,我們會新增多載函式定義,然後定義呼叫 Python 腳本所需的程序代碼。 函式會接受所有提供的參數,並將其傳遞至 Python 腳本。 腳本會以字串格式執行並傳回令牌。

#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 腳本

此文稿會透過 適用於 Python 的 Microsoft 驗證連結庫 (MSAL) 直接取得驗證令牌。 此程式代碼僅包含為取得驗證令牌以供範例應用程式使用的方法,且不適用於生產環境。 腳本僅適用於支援一般舊用戶名稱/密碼驗證的租使用者。 此腳本不支援 MFA 或憑證型驗證。

注意

執行此範例之前,您必須執行下列其中一個命令來安裝適用於 Python 的 MSAL:

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

最後,更新中的函AcquireOAuth2Token式以呼叫多載函式AcquireTokenAuthDelegateImpl 資源和授權單位 URL 是藉由讀取 challenge.GetResource()challenge.GetAuthority()來取得。 新增 OAuth2Challenge 引擎時,會傳入驗證委派。 此工作是由 SDK 完成,而且開發人員不需要額外的工作。

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;
}

engine新增 時,SDK 會呼叫 『AcquireOAuth2Token 函式、傳入挑戰、執行 Python 腳本、接收令牌,然後將令牌呈現給服務。