この例では、外部Python スクリプトを呼び出して OAuth 2.0 トークンを取得する方法を示します。 認証デリゲートの実装には、有効な OAuth 2.0 アクセス トークンが必要です。
前提条件
サンプルを実行するには
- Python 3.10 以降をインストールします。
- プロジェクトに utils.h/cpp を実装します。
- ビルド時にバイナリと同じディレクトリに、
auth.pyをプロジェクトに追加します。 - Microsoft Information Protection (MIP) SDK のセットアップと構成を完了します。 特に、クライアント アプリケーションを Microsoft Entra テナントに登録します。 Microsoft Entra IDは、トークン取得ロジックのアプリケーション ID (クライアント ID とも呼ばれます) を提供します。
このコードを運用環境で使用することは想定していません。 これは、開発用にのみ使用し、認証の概念を理解するために使用します。 サンプルはクロスプラットフォームです。
サンプル::auth::AcquireToken()
単純な認証の例では、パラメーターを受け取らず、ハードコーディングされたトークン値を返す単純な AcquireToken() 関数を示しています。 この例では、認証パラメーターを受け取り、外部Python スクリプトを呼び出してトークンを返すAcquireToken()をオーバーロードします。
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.
}
}
ユーザー入力またはアプリケーションは、最初の 3 つのパラメーターを提供します。 SDK は、認証デリゲートに最後の 2 つのパラメーターを提供します。
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 Authentication Library (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 関数を呼び出すために、AuthDelegateImpl の AcquireToken 関数を更新します。 リソースと機関の URL を取得するには、 challenge.GetResource() と challenge.GetAuthority() を読み取る。 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 スクリプトを実行し、トークンを受け取り、サービスにトークンを提示します。