Uzyskiwanie tokenu dostępu (Python)
W tym przykładzie pokazano, jak wywołać zewnętrzny skrypt języka Python w celu uzyskania tokenu OAuth2. Implementacja pełnomocnika uwierzytelniania wymaga prawidłowego tokenu dostępu OAuth2.
Wymagania wstępne
Aby uruchomić przykład poniżej:
- Zainstaluj język Python 2.7 lub nowszą.
- Zaimplej utils.h/cpp w projekcie.
- Auth.py powinny zostać dodane do projektu i istnieć w tym samym katalogu, w którym znajdują się pliki binarne w kompilacji.
- Ukończ konfigurację i konfigurację zestawu SDK (MIP). Między innymi zarejestrujesz aplikację kliencną w dzierżawie usługi Azure Active Directory (Azure AD). Usługa Azure AD udostępni identyfikator aplikacji, nazywany także identyfikatorem klienta, który jest używany w logiki pozyskiwania tokenu.
Ten kod nie jest przeznaczony do użytku produkcyjnego. Może być używana tylko do opracowywania i zrozumienia pojęć uwierzytelniania. Przykład to platforma międzyplatformowa.
przykład::auth::AcquireToken()
W przykładzie prostego uwierzytelniania pokazaliśmy prostą funkcję, która nie miała parametrów i zwróciła wartość tokenu o AcquireToken() trwałym kodzie. W tym przykładzie przeciążymy element AcquireToken(), aby zaakceptować parametry uwierzytelniania i wywołać zewnętrzny skrypt języka Python w celu zwrócenia tokenu.
auth.h
W uwierzytelniania.h jest przeciążona, a funkcja przeciążona i AcquireToken() zaktualizowane parametry są następujące:
//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.
}
}
Pierwsze trzy parametry będą udostępniane przez dane wejściowe użytkownika lub przez twardy kod aplikacji. Ostatnie dwa parametry są dostarczane przez zestaw SDK pełnomocnikowi uwierzytelniania.
auth.cpp
W pliku auth.cpp dodajemy definicję funkcji przeciążoną, a następnie definiujemy kod niezbędny do wywołania skryptu w języku Python. Funkcja akceptuje wszystkie podane parametry i przekazuje je do skryptu w języku Python. Skrypt wykona i zwróci token w formacie ciągu.
#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;
}
}
}
Skrypt języka Python
Ten skrypt uzyskuje tokeny uwierzytelniania bezpośrednio za pośrednictwem uwierzytelniania ADAL dla języka Python. Ten kod jest dostępny tylko w celu uzyskania tokenów uwierzytelniania do użycia w przykładowych aplikacjach i nie jest przeznaczony do użycia w środowisku produkcyjnym. Skrypt działa tylko w przypadku dzierżaw, które obsługują zwykłe stare uwierzytelnianie http nazwa_użytkownika/hasło. Uwierzytelnianie mfa lub uwierzytelnianie oparte na certyfikatach nie powiedzie się.
Uwaga
Przed uruchomieniem tego przykładu należy zainstalować aplikację ADAL dla języka Python, uruchamiając jedno z następujących poleceń:
pip install adal
pip3 install adal
import getopt
import sys
import json
import re
from adal import AuthenticationContext
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)
# Find everything after the last '/' and replace it with 'token'
if not authority.endswith('token'):
regex = re.compile('^(.*[\/])')
match = regex.match(authority)
authority = match.group()
authority = authority + username.split('@')[1]
auth_context = AuthenticationContext(authority)
token = auth_context.acquire_token_with_username_password(resource, username, password, clientId)
print(token["accessToken"])
if __name__ == '__main__':
main(sys.argv[1:])
Update AcquireOAuth2Token
Na koniec zaktualizuj AcquireOAuth2Token funkcję, AuthDelegateImpl aby wywołać funkcję AcquireToken przeciążenia. Adresy URL zasobów i urzędu są uzyskiwane na pomocą odczytu challenge.GetResource() i challenge.GetAuthority() . Po dodaniu aparatu jest on przekazywany do pełnomocnika OAuth2Challenge uwierzytelniania. Ta praca jest wykonywana przez zestaw SDK i nie wymaga dodatkowej pracy ze strony dewelopera.
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;
}
Po dodaniu zestaw SDK zadzwoni do funkcji "AcquireOAuth2Token", przechodząc do wyzwania, wykonując skrypt w języku Python, otrzymując token, a następnie przekazując engine go usłudze.