![](/img/trans.png)
[英]How to authenticate REST API in Azure Runbooks with Python?
[英]How do i authenticate to and get catalog from Azure Data Catalog using Rest API in Python
我想使用API從Azure數據目錄中獲取目錄的名稱。 當我嘗試使用以下命令從Azure數據目錄獲取目錄時
requests.get("https://management.azure.com/subscriptions/{id}/resourceGroups/{group_name}/providers/Microsoft.DataCatalog/catalogs/{catalogname}")
如鏈接https://docs.microsoft.com/en-us/rest/api/datacatalog/data-catalog-data-catalog所述
它引發以下錯誤
回應[400]
看來我必須先進行身份驗證。 如何在獲取目錄之前進行身份驗證?
要調用數據目錄REST操作,請創建AuthenticationContext實例並調用AcquireToken。 AuthenticationContext是Active Directory身份驗證庫NuGet包的一部分。 要在Visual Studio中安裝Active Directory身份驗證庫NuGet包,請運行
"Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory"
從NuGet軟件包管理器控制台。
這是獲取相同令牌的代碼。
static async Task<AuthenticationResult> AccessToken() { if (authResult == null) { //Resource Uri for Data Catalog API string resourceUri = "https://api.azuredatacatalog.com"; //To learn how to register a client app and get a Client ID, see https://msdn.microsoft.com/en-us/library/azure/mt403303.aspx#clientID string clientId = clientIDFromAzureAppRegistration; //A redirect uri gives AAD more details about the specific application that it will authenticate. //Since a client app does not have an external service to redirect to, this Uri is the standard placeholder for a client app. string redirectUri = "https://login.live.com/oauth20_desktop.srf"; // Create an instance of AuthenticationContext to acquire an Azure access token // OAuth2 authority Uri string authorityUri = "https://login.windows.net/common/oauth2/authorize"; AuthenticationContext authContext = new AuthenticationContext(authorityUri); // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint // AcquireToken takes a Client Id that Azure AD creates when you register your client app. authResult = await authContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Always)); } return authResult; }
這是獲取基於id的數據資產的示例代碼
// The Get Data Asset operation retrieves data asset by Id static JObject GetDataAsset(string assetUrl) { string fullUri = string.Format("{0}?api-version=2016-03-30", assetUrl); //Create a GET WebRequest as a Json content type HttpWebRequest request = WebRequest.Create(fullUri) as HttpWebRequest; request.KeepAlive = true; request.Method = "GET"; request.Accept = "application/json;adc.metadata=full"; try { var response = SetRequestAndGetResponse(request); using (var reader = new StreamReader(response.GetResponseStream())) { var itemPayload = reader.ReadToEnd(); Console.WriteLine(itemPayload); return JObject.Parse(itemPayload); } } catch (WebException ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.Status); if (ex.Response != null) { // can use ex.Response.Status, .StatusDescription if (ex.Response.ContentLength != 0) { using (var stream = ex.Response.GetResponseStream()) { using (var reader = new StreamReader(stream)) { Console.WriteLine(reader.ReadToEnd()); } } } } } return null; }
這是設置請求,令牌並獲得響應的方法。
static HttpWebResponse SetRequestAndGetResponse(HttpWebRequest request, string payload = null) { while (true) { //To authorize the operation call, you need an access token which is part of the Authorization header request.Headers.Add("Authorization", AccessToken().Result.CreateAuthorizationHeader()); //Set to false to be able to intercept redirects request.AllowAutoRedirect = false; if (!string.IsNullOrEmpty(payload)) { byte[] byteArray = Encoding.UTF8.GetBytes(payload); request.ContentLength = byteArray.Length; request.ContentType = "application/json"; //Write JSON byte[] into a Stream request.GetRequestStream().Write(byteArray, 0, byteArray.Length); } else { request.ContentLength = 0; } HttpWebResponse response = request.GetResponse() as HttpWebResponse; // Requests to **Azure Data Catalog (ADC)** may return an HTTP 302 response to indicate // redirection to a different endpoint. In response to a 302, the caller must re-issue // the request to the URL specified by the Location response header. if (response.StatusCode == HttpStatusCode.Redirect) { string redirectedUrl = response.Headers["Location"]; HttpWebRequest nextRequest = WebRequest.Create(redirectedUrl) as HttpWebRequest; nextRequest.Method = request.Method; request = nextRequest; } else { return response; } } }
基本上,您需要獲取承載令牌並將其作為請求參數傳遞,以使用Azure Data Catalog API獲取目錄。
有關更多代碼示例,請瀏覽下面的代碼庫。
https://github.com/Azure-Samples/data-catalog-dotnet-get-started
希望能幫助到你。
在python中添加新答案
為了在python中獲取身份驗證上下文,您可以執行以下操作
這是調用圖形api時所需的參數設置。
RESOURCE = "https://graph.microsoft.com" # Add the resource you want the access token for TENANT = "Your tenant" # Enter tenant name, eg contoso.onmicrosoft.com AUTHORITY_HOST_URL = "https://login.microsoftonline.com" CLIENT_ID = "Your client id " # copy the Application ID of your app from your Azure portal CLIENT_SECRET = "Your client secret" # copy the value of key you generated when setting up the application # These settings are for the Microsoft Graph API Call API_VERSION = 'v1.0'
這是登錄代碼
AUTHORITY_URL = config.AUTHORITY_HOST_URL + '/' + config.TENANT REDIRECT_URI = 'http://localhost:{}/getAToken'.format(PORT) TEMPLATE_AUTHZ_URL = ('https://login.microsoftonline.com/{}/oauth2/authorize?' + 'response_type=code&client_id={}&redirect_uri={}&' + 'state={}&resource={}')
def login():
auth_state = str(uuid.uuid4())
flask.session['state'] = auth_state
authorization_url = TEMPLATE_AUTHZ_URL.format(
config.TENANT,
config.CLIENT_ID,
REDIRECT_URI,
auth_state,
config.RESOURCE)
resp = flask.Response(status=307)
resp.headers['location'] = authorization_url
return resp
這是您如何檢索令牌的方法
auth_context = adal.AuthenticationContext(AUTHORITY_URL)
token_response = auth_context.acquire_token_with_authorization_code(code, REDIRECT_URI, config.RESOURCE,
config.CLIENT_ID, config.CLIENT_SECRET)
然后可以為您的Azure數據目錄api創建一個端點。 這是相同的http標頭-
http_headers = {'Authorization': 'Bearer ' + token_response['accessToken'],
'User-Agent': 'adal-python-sample',
'Accept': 'application/json',
'Content-Type': 'application/json',
'client-request-id': str(uuid.uuid4())}
最后,您可以調用api。 這里的端點是數據目錄API URL。
data = requests.get(endpoint, headers=http_headers, stream=False).json()
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.