Skip to content

Commit 4ade6bf

Browse files
committed
wip 3101
1 parent 68fa466 commit 4ade6bf

File tree

2 files changed

+124
-161
lines changed

2 files changed

+124
-161
lines changed

articles/azure-monitor/essentials/rest-api-walkthrough.md

Lines changed: 54 additions & 159 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ The Azure Monitor API also makes it possible to list alert rules, view activity
2020

2121
Tasks executed using the Azure Monitor API use the Azure Resource Manager authentication model. All requests must be authenticated with Azure Active Directory (Azure Active Directory). One approach to authenticating the client application is to create an Azure Active Directory service principal and retrieve the authentication (JWT) token.
2222

23-
## Create an service principal
23+
## Create an Azure Active Directory service principal
2424

2525
### [Azure Portal](#tab/portal)
2626

@@ -29,7 +29,6 @@ To create an Azure Active Directory service principal using the Azure Portal see
2929
### [Azure CLI](#tab/cli)
3030

3131

32-
##
3332
Run the following script to create a service principal and app.
3433

3534
```azurecli
@@ -62,10 +61,17 @@ The example below assigns the `Reader` role to the service principal for all res
6261
For more information on creating a service principal using Azure CLI, see [Create an Azure service principal with the Azure CLI](https://learn.microsoft.com/cli/azure/create-an-azure-service-principal-azure-cli)
6362

6463

64+
### [Powershell](#tab/powershell)
6565

66-
To retrieve an access token using a REST call submit the following request using the `appId` and `password`:
66+
To create an Azure Active Directory service principal using thePowershell see [using Azure PowerShell to create a service principal to access resources](/powershell/azure/create-azure-service-principal-azureps). It's also possible to [create a service principal via the Azure portal](../../active-directory/develop/howto-create-service-principal-portal.md).
6767

68-
```http
68+
---
69+
70+
## Retrieve a token
71+
72+
To retrieve an access token using a REST call submit the following request using the `appId` and `password` for your servide pricipal and app:
73+
74+
```HTTP
6975
7076
POST /<appId>/oauth2/v2.0/token
7177
Host: https://login.microsoftonline.com
@@ -91,136 +97,18 @@ curl --location --request POST 'https://login.microsoftonline.com/a1234bcd-5849-
9197
```
9298
A successful request receives an access token in the response:
9399

94-
```http
100+
```HTTP
95101
{
96102
token_type": "Bearer",
97103
"expires_in": "86399",
98104
"ext_expires_in": "86399",
99105
"access_token": ""eyJ0eXAiOiJKV1QiLCJ.....Ax"
100106
}
101107
```
102-
Use the access token in your Azure Monitor API requests
103-
104-
### [Powershell](#tab/powershell)
105-
The following sample script demonstrates creating an Azure Active Directory service principal via PowerShell. For a more detailed walkthrough, see the documentation on [using Azure PowerShell to create a service principal to access resources](/powershell/azure/create-azure-service-principal-azureps). It's also possible to [create a service principal via the Azure portal](../../active-directory/develop/howto-create-service-principal-portal.md).
106-
107-
108-
```powershell
109-
$subscriptionId = "{azure-subscription-id}"
110-
$resourceGroupName = "{resource-group-name}"
111-
112-
# Authenticate to a specific Azure subscription.
113-
Connect-AzAccount -SubscriptionId $subscriptionId
114-
115-
# Password for the service principal
116-
$pwd = "{service-principal-password}"
117-
$secureStringPassword = ConvertTo-SecureString -String $pwd -AsPlainText -Force
118-
119-
# Create a new Azure Active Directory application
120-
$azureAdApplication = New-AzADApplication `
121-
-DisplayName "My Azure Monitor" `
122-
-HomePage "https://localhost/azure-monitor" `
123-
-IdentifierUris "https://localhost/azure-monitor" `
124-
-Password $secureStringPassword
125-
126-
# Create a new service principal associated with the designated application
127-
New-AzADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId
128-
129-
# Assign Reader role to the newly created service principal
130-
New-AzRoleAssignment -RoleDefinitionName Reader `
131-
-ServicePrincipalName $azureAdApplication.ApplicationId.Guid
132-
133-
```
134-
135-
To query the Azure Monitor API, the client application should use the previously created service principal to authenticate. The following example PowerShell script shows one approach that uses the [Microsoft Authentication Library (MSAL)](../../active-directory/develop/msal-overview.md) to obtain the authentication token.
136-
137-
```powershell
138-
$ClientID = "{client_id}"
139-
$loginURL = "https://login.microsoftonline.com"
140-
$tenantdomain = "{tenant_id}"
141-
$CertPassWord = "{password_for_cert}"
142-
$certPath = "C:\temp\Certs\testCert_01.pfx"
143-
144-
[string[]] $Scopes = "https://graph.microsoft.com/.default"
145-
146-
Function Load-MSAL {
147-
if ($PSVersionTable.PSVersion.Major -gt 5)
148-
{
149-
$core = $true
150-
$foldername = "netcoreapp2.1"
151-
}
152-
else
153-
{
154-
$core = $false
155-
$foldername = "net45"
156-
}
157-
158-
# Download MSAL.Net module to a local folder if it does not exist there
159-
if ( ! (Get-ChildItem $HOME/MSAL/lib/Microsoft.Identity.Client.* -erroraction ignore) ) {
160-
install-package -Source nuget.org -ProviderName nuget -SkipDependencies Microsoft.Identity.Client -Destination $HOME/MSAL/lib -force -forcebootstrap | out-null
161-
}
162-
163-
# Load the MSAL assembly -- needed once per PowerShell session
164-
[System.Reflection.Assembly]::LoadFrom((Get-ChildItem $HOME/MSAL/lib/Microsoft.Identity.Client.*/lib/$foldername/Microsoft.Identity.Client.dll).fullname) | out-null
165-
}
166-
167-
Function Get-GraphAccessTokenFromMSAL {
168-
169-
Load-MSAL
170-
171-
$global:app = $null
172-
173-
$x509cert = [System.Security.Cryptography.X509Certificates.X509Certificate2] (GetX509Certificate_FromPfx -CertificatePath $certPath -CertificatePassword $CertPassWord)
174-
write-host "Cert = {$x509cert}"
175-
176-
$ClientApplicationBuilder = [Microsoft.Identity.Client.ConfidentialClientApplicationBuilder]::Create($ClientID)
177-
[void]$ClientApplicationBuilder.WithAuthority($("$loginURL/$tenantdomain"))
178-
[void]$ClientApplicationBuilder.WithCertificate($x509cert)
179-
$global:app = $ClientApplicationBuilder.Build()
180-
181-
[Microsoft.Identity.Client.AuthenticationResult] $authResult = $null
182-
$AquireTokenParameters = $global:app.AcquireTokenForClient($Scopes)
183-
try {
184-
$authResult = $AquireTokenParameters.ExecuteAsync().GetAwaiter().GetResult()
185-
}
186-
catch {
187-
$ErrorMessage = $_.Exception.Message
188-
Write-Host $ErrorMessage
189-
}
190-
191-
return $authResult
192-
}
193-
194-
function GetX509Certificate_FromPfx($CertificatePath, $CertificatePassword){
195-
#write-host "Path: '$CertificatePath'"
196-
197-
if(![System.IO.Path]::IsPathRooted($CertificatePath))
198-
{
199-
$LocalPath = Get-Location
200-
$CertificatePath = "$LocalPath\$CertificatePath"
201-
}
202-
203-
#Write-Host "Looking for '$CertificatePath'"
204-
205-
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($CertificatePath, $CertificatePassword)
206-
207-
Return $certificate
208-
}
209-
210-
$myvar = Get-GraphAccessTokenFromMSAL
211-
Write-Host "Access Token: " $myvar.AccessToken
212-
213-
```
214-
215-
Loading the certificate from a .pfx file in PowerShell can make it easier for an admin to manage certificates without having to install the certificate in the certificate store. However, this step shouldn't be done on a client machine because the user could potentially discover the file and the password for it and the method to authenticate. The client credentials flow is only intended to be run in a back-end service-to-service type of scenario where only admins have access to the machine.
216108

217-
---
218109

219110

220-
After authenticating and retrieving a token, queries can then be executed against the Azure Monitor REST API.
221-
For metrics, the two most used queries are:
222-
- List the metric definitions for a resource.
223-
- Retrieve the metric values.
111+
After authenticating and retrieving a token, use the access token in your Azure Monitor API requests.
224112

225113
> [!NOTE]
226114
> For more information on working with the Azure REST API, see the [Azure REST API reference](/rest/api/azure/).
@@ -230,29 +118,23 @@ For metrics, the two most used queries are:
230118

231119
Use the [Azure Monitor Metric Definitions REST API](/rest/api/monitor/metricdefinitions) to access the list of metrics that are available for a service.
232120

233-
**Method**: GET
234-
235-
**Request URI**: https:\/\/management.azure.com/subscriptions/*{subscriptionId}*/resourceGroups/*{resourceGroupName}*/providers/*{resourceProviderNamespace}*/*{resourceType}*/*{resourceName}*/providers/microsoft.insights/metricDefinitions?api-version=*{apiVersion}*
236-
237-
To retrieve the metric definitions for an Azure Storage account, the request would appear as the following example:
238-
239-
```powershell
240-
$request = "https://management.azure.com/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metricDefinitions?api-version=2018-01-01"
121+
```HTTP
122+
GET /subscriptions/<subscription id>/resourcegroups/<resourceGroupName>/providers/<resourceProviderNamespace>/<resourceType>/<resourceName>/providers/microsoft.insights/metricDefinitions?api-version=<apiVersion>
123+
Host: management.azure.com
124+
Content-Type: application/json
125+
Authorization: Bearer <access token>
241126
127+
```
242128

243-
Invoke-RestMethod -Uri $request `
244-
-Headers $authHeader `
245-
-Method Get `
246-
-OutFile ".\contosostorage-metricdef-results.json" `
247-
-Verbose
129+
For example, The request below retrieves the metric definitions for an Azure Storage account
248130

131+
```curl
132+
curl --location --request GET 'https://management.azure.com/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metricDefinitions?api-version=2018-01-01'
133+
--header 'Authorization: Bearer eyJ0eXAiOi...xYz
249134
```
250135

251-
> [!NOTE]
252-
> Older versions of the metric definitions API didn't support dimensions. We recommend using API version "2018-01-01" or later.
253-
>
254-
255-
The resulting JSON response body would be similar to the following example (note that the second metric has dimensions):
136+
The following JSON shows an example response body.
137+
In this example, only the second metric has dimensions.
256138

257139
```json
258140
{
@@ -362,34 +244,40 @@ The resulting JSON response body would be similar to the following example (note
362244
]
363245
}
364246
```
247+
> [!NOTE]
248+
> We recommend using API version "2018-01-01" or later. Older versions of the metric definitions API don't support dimensions.
365249
366250
## Retrieve dimension values
367251

368-
After the available metric definitions are known, there might be some metrics that have dimensions. Before you query for the metric, you might want to discover the range of values that a dimension has. Based on these dimension values, you can then choose to filter or segment the metrics based on dimension values while you query for metrics. Use the [Azure Monitor Metrics REST API](/rest/api/monitor/metrics) to find all the possible values for a given metric dimension.
252+
After the retrieving the available metric definitions for metrics with dimensions, retrieve the range of values for the dimensions. Use the dimension values to filter or segment the metrics based in your queries. Use the [Azure Monitor Metrics REST API](/rest/api/monitor/metrics) to find all the possible values for a given metric dimension.
369253

370254
Use the metric's name `value` (not `localizedValue`) for any filtering requests. If no filters are specified, the default metric is returned. The use of this API only allows one dimension to have a wildcard filter. The key difference between a dimension values request and a metric data request is specifying the `"resultType=metadata"` query parameter.
371255

372256
> [!NOTE]
373257
> To retrieve dimension values by using the Azure Monitor REST API, use the API version "2019-07-01" or later.
374258
>
375259
376-
**Method**: GET
377-
378-
**Request URI**: https\://management.azure.com/subscriptions/*{subscription-id}*/resourceGroups/*{resource-group-name}*/providers/*{resource-provider-namespace}*/*{resource-type}*/*{resource-name}*/providers/microsoft.insights/metrics?metricnames=*{metric}*&timespan=*{starttime/endtime}*&$filter=*{filter}*&resultType=metadata&api-version=*{apiVersion}*
379-
380-
For example, to retrieve the list of dimension values that were emitted for the `API Name` dimension for the `Transactions` metric, where the GeoType dimension = `Primary` during the specified time range, the request would be:
381-
382-
```powershell
383-
$filter = "APIName eq '*' and GeoType eq 'Primary'"
384-
$request = "https://management.azure.com/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metrics?metricnames=Transactions&timespan=2018-03-01T00:00:00Z/2018-03-02T00:00:00Z&resultType=metadata&`$filter=GeoType eq 'Primary' and ApiName eq '*'&api-version=2019-07-01"
385-
Invoke-RestMethod -Uri $request `
386-
-Headers $authHeader `
387-
-Method Get `
388-
-OutFile ".\contosostorage-dimension-values.json" `
389-
-Verbose
260+
```HTTP
261+
GET /subscriptions/<subscription-id>/resourceGroups/
262+
<resource-group-name>/providers/<resource-provider-namespace>/
263+
<resource-type>/<resource-name>/providers/microsoft.insights/
264+
metrics?metricnames=<metric>
265+
&timespan=<starttime/endtime>
266+
&$filter=<filter>
267+
&resultType=metadata
268+
&api-version=<apiVersion> HTTP/1.1
269+
Host: management.azure.com
270+
Content-Type: application/json
271+
Authorization: Bearer <access token>
390272
```
273+
For example, to retrieve the list of dimension values that were emitted for the `API Name` dimension for the `Transactions` metric, where the GeoType dimension = `Primary` during the specified time range, the request would be:
391274

392-
The resulting JSON response body would be similar to the following example:
275+
```curl
276+
curl --location --request GET 'https://management.azure.com/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metrics?metricnames=Transactions&timespan=2018-03-01T00:00:00Z/2018-03-02T00:00:00Z&resultType=metadata&$filter=GeoType eq \'Primary\' and ApiName eq \'*\'&api-version=2019-07-01'
277+
-header 'Content-Type: application/json' \
278+
--header 'Authorization: Bearer eyJ0e..meG1lWm9Y
279+
```
280+
The following JSON shows an example response body.
393281

394282
```json
395283
{
@@ -445,9 +333,16 @@ Use the metric's name `value` (not `localizedValue`) for any filtering requests.
445333
> To retrieve multi-dimensional metric values using the Azure Monitor REST API, use the API version "2019-07-01" or later.
446334
>
447335
336+
```HTTP
337+
GET /subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/<resource-provider-namespace>/<resource-type>/<resource-name>/providers/microsoft.insights/metrics?metricnames=<metric>&timespan=<starttime/endtime>&$filter=<filter>&interval=<timeGrain>&aggregation=<aggreation>&api-version=<apiVersion>
338+
Host: management.azure.com
339+
Content-Type: application/json
340+
Authorization: Bearer <access token>
341+
```
342+
448343
**Method**: GET
449344

450-
**Request URI**: https:\//management.azure.com/subscriptions/*{subscription-id}*/resourceGroups/*{resource-group-name}*/providers/*{resource-provider-namespace}*/*{resource-type}*/*{resource-name}*/providers/microsoft.insights/metrics?metricnames=*{metric}*&timespan=*{starttime/endtime}*&$filter=*{filter}*&interval=*{timeGrain}*&aggregation=*{aggreation}*&api-version=*{apiVersion}*
345+
**Request URI**:
451346

452347
For example, to retrieve the top three APIs, in descending value, by the number of `Transactions` during a 5-minute range, where the GeoType was `Primary`, the request would be:
453348

articles/azure-monitor/logs/api/register-app-for-token.md

Lines changed: 70 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ To access Azure REST APIs such as the Log analytics API, or to send custom metri
1313

1414
## Register an App
1515

16+
Create a service proncipal and refister an usign the Azure Portal, Azure CLI, or Powershell.
17+
### [Azure Portal](#tab/portal)
18+
1619
1. To register an app, open the Active Directory Overview page in the Azure portal.
1720

1821
1. Select **App registrations** from the side bar.
@@ -38,10 +41,75 @@ To access Azure REST APIs such as the Log analytics API, or to send custom metri
3841
:::image type="content" source="../media/api-register-app/client-secret.png" alt-text="A screenshot showing the client secrets page.":::
3942

4043

44+
### [Azure CLI](#tab/cli)
45+
46+
47+
Run the following script to create a service principal and app.
48+
49+
```azurecli
50+
az ad sp create-for-rbac -n <Service principal display name>
51+
52+
```
53+
The response looks as follows:
54+
```JSON
55+
{
56+
"appId": "0a123b56-c987-1234-abcd-1a2b3c4d5e6f",
57+
"displayName": "AzMonAPIApp",
58+
"password": "123456.ABCDE.~XYZ876123ABcEdB7169",
59+
"tenant": "a1234bcd-5849-4a5d-a2eb-5267eae1bbc7"
60+
}
61+
62+
```
63+
>[!Important]
64+
> The output includes credentials that you must protect. Be sure that you do not include these credentials in your code or check the credentials into your source control.
65+
66+
Add a role and scope for the resources that you want to access using the API
67+
68+
```azurecli
69+
az role assignment create --assignee <`appId`> --role <Role> --scope <resource URI>
70+
```
71+
72+
The example below assigns the `Reader` role to the service principal for all resources in the `rg-001`resource group:
73+
```azurecli
74+
az role assignment create --assignee 0a123b56-c987-1234-abcd-1a2b3c4d5e6f --role Reader --scope '\/subscriptions/a1234bcd-5849-4a5d-a2eb-5267eae1bbc7/resourceGroups/rg-001'
75+
```
76+
For more information on creating a service principal using Azure CLI, see [Create an Azure service principal with the Azure CLI](https://learn.microsoft.com/cli/azure/create-an-azure-service-principal-azure-cli)
77+
78+
### [Powershell](#tab/powershell)
79+
The following sample script demonstrates creating an Azure Active Directory service principal via PowerShell. For a more detailed walkthrough, see the documentation on [using Azure PowerShell to create a service principal to access resources](/powershell/azure/create-azure-service-principal-azureps). It's also possible to [create a service principal via the Azure portal](../../active-directory/develop/howto-create-service-principal-portal.md).
80+
81+
82+
```powershell
83+
$subscriptionId = "{azure-subscription-id}"
84+
$resourceGroupName = "{resource-group-name}"
85+
86+
# Authenticate to a specific Azure subscription.
87+
Connect-AzAccount -SubscriptionId $subscriptionId
88+
89+
# Password for the service principal
90+
$pwd = "{service-principal-password}"
91+
$secureStringPassword = ConvertTo-SecureString -String $pwd -AsPlainText -Force
92+
93+
# Create a new Azure Active Directory application
94+
$azureAdApplication = New-AzADApplication `
95+
-DisplayName "My Azure Monitor" `
96+
-HomePage "https://localhost/azure-monitor" `
97+
-IdentifierUris "https://localhost/azure-monitor" `
98+
-Password $secureStringPassword
99+
100+
# Create a new service principal associated with the designated application
101+
New-AzADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId
102+
103+
# Assign Reader role to the newly created service principal
104+
New-AzRoleAssignment -RoleDefinitionName Reader `
105+
-ServicePrincipalName $azureAdApplication.ApplicationId.Guid
106+
107+
```
108+
---
109+
41110
## Next steps
42111

43-
Before you can generate a token using your app, client ID, and secret, assign the app to a role using Access control (IAM) for resource that you want to access.
44-
The role will depend on the resource type and the API that you want to use.
112+
Before you can generate a token using your app, client ID, and secret, assign the app to a role using Access control (IAM) for resource that you want to access. The role will depend on the resource type and the API that you want to use.
45113
For example,
46114
- To grant your app read from a Log Analytics Workspace, add your app as a member to the **Reader** role using Access control (IAM) for your Log Analytics Workspace. For more information, see [Access the API](./access-api.md)
47115

0 commit comments

Comments
 (0)