此示例演示如何调用外部Python脚本以获取 OAuth 2.0 令牌。 身份验证委托实现需要有效的 OAuth 2.0 访问令牌。
先决条件
若要运行该示例:
- 安装 Python 3.10 或更高版本。
- 在项目中实现 utils.h/cpp。
- 将
auth.py添加到项目中,并在构建时将其放在与二进制文件相同的目录中。 - 完成 Microsoft信息保护 (MIP) SDK 设置和配置。 在其他任务之外,您在 Microsoft Entra 租户中注册客户端应用程序。 Microsoft Entra ID为令牌获取逻辑提供应用程序 ID(也称为客户端 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脚本
此脚本使用 Microsoft 身份验证库 (MSAL) 直接获取Python的身份验证令牌。 此代码仅用于获取身份验证令牌供示例应用使用,不适用于生产环境。 该脚本仅适用于支持用户名/密码身份验证的租户。 该脚本不支持多重身份验证(MFA)或基于证书的身份验证。
注释
运行此示例之前,请运行以下命令之一安装 MSAL for Python:
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中更新AuthDelegateImpl函数,以调用重载的AcquireToken函数。 读取 challenge.GetResource() 和 challenge.GetAuthority() 以获取资源和颁发机构 URL。 SDK 在添加引擎时将 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;
}
SDK 添加 engine时,它将调用该 AcquireOAuth2Token 函数。 该函数传入质询值,运行 Python 脚本,接收令牌,并将该令牌提交给服务。