List Cloud Service Classic use PowerShell and Azure Rest API - azure

I Have a problem. Could you please help me view list Cloud Service Classic use PowerShell and Azure Rest API. When I used script for Web APP I show list Web APP, but when I used scrip for Cloud Service Classic I show error.
# Variables
$TenantId = "" # Enter Tenant Id.
$ClientId = "" # Enter Client Id.
$ClientSecret = "" # Enter Client Secret.
$Resource = "https://management.core.windows.net/"
$SubscriptionId = "" # Enter Subscription Id.
$RequestAccessTokenUri = "https://login.microsoftonline.com/$TenantId/oauth2/token"
$body = "grant_type=client_credentials&client_id=$ClientId&client_secret=$ClientSecret&resource=$Resource"
$Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType 'application/x-www-form-urlencoded'
Write-Host "Print Token" -ForegroundColor Green
Write-Output $Token
# Get Azure Resource Groups
$ResourceGroupApiUri = "https://management.core.windows.net/$SubscriptionId/services/hostedservices"
$Headers = #{}
$Headers.Add("Authorization","$($Token.token_type) "+ " " + "$($Token.access_token)")
$ResourceGroups = Invoke-RestMethod -Method Get -Uri $ResourceGroupApiUri -Headers $Headers
Write-Host "Print Resource groups" -ForegroundColor Green
Write-Output $ResourceGroups
Invoke-RestMethod : ForbiddenErrorThe server failed to authenticate the request. Verify that the certificate is valid and
is associated with this subscription.

Actually, there is a built-in ASM PowerShell to list the cloud services associated with the current subscription.
Get-AzureService
Reference - https://learn.microsoft.com/en-us/powershell/module/servicemanagement/azure/get-azureservice?view=azuresmps-4.0.0
Besides, if you insist on calling the ASM rest api with powershell, you could refer to this article, the sample calls the Get Deployment api, just change it to List Cloud Services.
#Request Headers required to invoke the GET DEPLOYMENT REST API
$method
=
“GET”
$headerDate
= ‘2009-10-01’
$headers
= #{“x-ms-version”=“$headerDate“}
#Retrieving the subscription ID
$subID
= (Get-AzureSubscription
-Current).SubscriptionId
$URI
=
https://management.core.windows.net/$subID/services/hostedservices/kaushalz/deployments/4f006bb7d2874dd4895f77a97b7938d0
#Retrieving the certificate from Local Store
$cert
= (Get-ChildItem
Cert:\CurrentUser\My
|
?{$_.Thumbprint -eq
“B4D460D985F1D07A6B9F8BFD67E36BC53A4490FC”}).GetRawCertData()
#converting the raw cert data to BASE64
body
=
“<Binary>—–BEGIN CERTIFICATE—–`n$([convert]::ToBase64String($cert))`n—–END CERTIFICATE—–</Binary>”
#Retrieving the certificate ThumbPrint
$mgmtCertThumb
= (Get-AzureSubscription
-Current).Certificate.Thumbprint
#Passing all the above parameters to Invoke-RestMethod cmdlet
Invoke-RestMethod
-Uri
$URI
-Method
$method
-Headers
$headers
-CertificateThumbprint
” B4D460D985F1D07A6B9F8BFD67E36BC53A4490FC”
-ContentType
$ContentType

Related

Azure AutomationAccount DSC scripts debug

I am running a DSC script from an Azure automation account to configure Windows VMs. It downloads files from a storage account in Azure to hosts for more configurations. If I hardcode the storage SAS token, it works fine. But I would like to get the SAS token in the DSC script. I use managed identity of the Automation account and assigned proper IAM access in storage account. I am able to get the SAS token in a test runbook script, but not in DSC script.
I got the main part of the code from
https://learn.microsoft.com/en-us/azure/automation/enable-managed-identity-for-automation
The error I am getting indicates that the SAS token is not generated correctly, but I can't find a way to see what the error msgs are from this part of the code in DSC when it executed.
any help/suggestion is appreciated!
Configuration DSCtest {
Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
$resource= "?resource=https://management.azure.com/"
$url = $env:IDENTITY_ENDPOINT + $resource
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("X-IDENTITY-HEADER", $env:IDENTITY_HEADER)
$Headers.Add("Metadata", "True")
$accessToken = Invoke-RestMethod -Uri $url -Method 'GET' -Headers $Headers
$Atoken = $accessToken.access_token
Write-Output $Atoken
$toDate = (Get-Date).AddDays(4).toString("yyyy-MM-ddT00:00:00Z")
$params = #{canonicalizedResource="/file/storageacnt/exec";signedResource="c";signedPermission="rcw";signedProtocol="https";signedExpiry=$toDate}
$jsonParams = $params | ConvertTo-Json
$sasResponse = Invoke-WebRequest -Uri https://management.azure.com/subscriptions/xxxxxxxxxxxx/resourceGroups/rg-xxxxx/providers/Microsoft.Storage/storageAccounts/storageaccnt/listServiceSas/?api-version=2017-06-01 -Method POST -Body $jsonParams -Headers #{Authorization="Bearer $Atoken"} -UseBasicParsing
$sasContent = $sasResponse.Content | ConvertFrom-Json
$sasCred = $sasContent.serviceSasToken
write-host $sasCred
$sasToken = "?$sasCred"
Node LocalHost {
....

Export all API names Azure APIM

I am trying to export all the url endpoints of my APIs which are stored in Azure APIM.
I need them listed in the format [POST]: https://apim-resource-name.azure-api.net/api-name/api-function, or something similar, so I am trying to enumerate all the endpoints first and the VERB that can be used much like what SwaggerUI or one of the OpenAPI docs might show.
I have this code so far but cannot get the output I would like, am I on the right track or is there any easier way to do this even via UI? I have also tried exporting the template and parsing the script, but it seemed overly complicated for this task.
#az login
$token = az account get-access-token | ConvertFrom-Json
$token = $token.accessToken -replace "`n","" -replace "`r",""
$headers = #{Authorization="Bearer $token.accessToken"}
$subscriptionId = 'subscriptionid'
$resourceGroupName = 'resourcegroupname'
$resourceName = 'resourcename'
$apiName = 'apiname'
$url_getapiexport = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.ApiManagement/service/$resourceName/apis/$apiName`?format=swagger-link&export=true&api-version=2021-08-01" #GET
$url_getapiexport
#Invoke-RestMethod -Uri $url_getapiexport -Method GET -Headers #{Authorization="Bearer $token"} -ContentType "application/json"
$url_getapibytags = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.ApiManagement/service/$resourceName/apisByTags?&includeNotTaggedApis=true&api-version=2021-08-01" #GET
$url_getapibytags
$api_tags = Invoke-RestMethod -Uri $url_getapibytags -Method GET -Headers #{Authorization="Bearer $token"} -ContentType "application/json"
$api_tags
foreach ($api in $api_tags) {
write-host API: $api.value.api.name
}
So if you want to export all APIM APIs and their service URLs you can do like this (replace xxx with correct values). Example in PHP
<?php
echo "[INFO] API Names and Service Urls \n\n";
$apiList = shell_exec('az apim api list --resource-group "xxx" --service-name "xxx" ');
$apis = json_decode($apiList, true);
$cli = "az rest --method get --url";
foreach ($apis as $api)
{
$name = $api["name"];
$apiRequest = "$cli " . "\"https://management.azure.com/subscriptions/xxx/resourceGroups/xxx/providers/Microsoft.ApiManagement/service/xxx/apis/$name?api-version=2021-08-01\"";
$json = shell_exec($apiRequest);
$apiInfo = json_decode($json, true);
$displayName = $apiInfo["properties"]["displayName"];
$serviceUrl = $apiInfo["properties"]["serviceUrl"];
printf("%s: %s \n", $displayName, $serviceUrl);
}
?>

How to get the access token to Azure API Management programmatically?

I'm trying to implement Azure Active Directory in my API Management instance using the Protect an API by using OAuth 2.0 with Azure Active Directory and API Management doc. The doc suggests that in order to get the access token I need to use the Developer Portal.
My problem is: An external application is going to communicate with API Management. Is there a way to omit the Developer Portal and get the access token programmatically?
It's a pain but thanks to Jos Lieben I am able to do it with this Powershell function
It's specifically for granting API access on behalf of the Org, but as you can see you can extract the commands to get and use the API token.
Original Author Link: https://www.lieben.nu/liebensraum/2018/04/how-to-grant-oauth2-permissions-to-an-azure-ad-application-using-powershell-unattended-silently/
Function Grant-OAuth2PermissionsToApp{
Param(
[Parameter(Mandatory=$true)]$Username, #global administrator username
[Parameter(Mandatory=$true)]$Password, #global administrator password
[Parameter(Mandatory=$true)]$azureAppId #application ID of the azure application you wish to admin-consent to
)
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($Username, $secpasswd)
$res = login-azurermaccount -Credential $mycreds
$context = Get-AzureRmContext
$tenantId = $context.Tenant.Id
$refreshToken = #($context.TokenCache.ReadItems() | where {$_.tenantId -eq $tenantId -and $_.ExpiresOn -gt (Get-Date)})[0].RefreshToken
$body = "grant_type=refresh_token&refresh_token=$($refreshToken)&resource=74658136-14ec-4630-ad9b-26e160ff0fc6"
$apiToken = Invoke-RestMethod "https://login.windows.net/$tenantId/oauth2/token" -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'
$header = #{
'Authorization' = 'Bearer ' + $apiToken.access_token
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()
}
$script:url = "https://main.iam.ad.ext.azure.com/api/RegisteredApplications/$azureAppId/Consent?onBehalfOfAll=true"
Invoke-RestMethod -Uri $url -Headers $header -Method POST -ErrorAction Stop
}

How to add Extension Properties for Azure-AD Device Objects using PowerShell?

I want to add extension properties for device objects in Azure AD using Power-Shell. I have search a lot but found examples for only User objects.I have written a script and its successful for User Objects but am not be able to set extension properties for Device.
A command Set-AzureADUserExtension
exists for User but for devices, there is no such commands e.g
Set-AzureADDeviceExtension
(there is no command exists like it). Can anyone help me how to achieve this?How can i set extension properties for Device Objects?
I want to achieve something like this:
New-AzureADApplicationExtensionProperty -ObjectId $MyApp -Name "MyNewProperty" -DataType "String" -TargetObjects "Device";
Set-AzureADDeviceExtension -ObjectId $deviceId -ExtensionName "extension_0380f0f700c040b5aa577c9268940b53_MyNewProperty" -ExtensionValue "MyNewValue";
I was looking for exactly the same and I did not find anything then and today either. I had to use the Microsoft Graph API to add new extensions to the device object. The same for consulting.
Step 1: Install or import the azure module.
Install-Module AzureAD
or
Import-Module AzureAD
Step 2: Search Object and save ObjectID.
$ObjectID = (Get-AzureADDevice -SearchString 'Object-Name').ObjectId
Note: The "id" in the request is the "id" property of the device, not the "deviceId" property.
Step 3: Create App
https://portal.azure.com - Azure Active Directory - App registrations - New registration
Name: YourAppName
Supported account types: Accounts in this organizational directory only (Default Directory)
Redirect URI: (WEB) https://login.microsoftonline.com/common/oauth2/nativeclient
Step 4: Configure App
https://portal.azure.com - Azure Active Directory - App registrations - YourAppName
Certificates & secrets - New client secret
Save client secret value
API permissions - Add a permission - Microsoft Graph - Delegated permissions
Directory.AccessAsUser.All
Step 5: Get access_token
## Directory.AccessAsUser.All : Minimun privilege for Get, add, update and delete extensions. (https://learn.microsoft.com/en-us/graph/api/opentypeextension-post-opentypeextension?view=graph-rest-1.0)
$scopes = "Directory.AccessAsUser.All"
$redirectURL = "https://login.microsoftonline.com/common/oauth2/nativeclient"
$clientID = "YourAppIdClient"
$clientSecret = [System.Web.HttpUtility]::UrlEncode("YourAppClientSecret")
$authorizeUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
$requestUrl = $authorizeUrl + "?scope=$scopes"
$requestUrl += "&response_type=code"
$requestUrl += "&client_id=$clientID"
$requestUrl += "&redirect_uri=$redirectURL"
$requestUrl += "&response_mode=query"
Write-Host
Write-Host "Copy the following URL and paste the following into your browser:"
Write-Host
Write-Host $requestUrl -ForegroundColor Cyan
Write-Host
Write-Host "Copy the code querystring value from the browser and paste it below."
Write-Host
$code = Read-Host -Prompt "Enter the code"
$body = "client_id=$clientID&client_secret=$clientSecret&scope=$scopes&grant_type=authorization_code&code=$code&redirect_uri=$redirectURL"
$tokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
$response = Invoke-RestMethod -Method Post -Uri $tokenUrl -Headers #{"Content-Type" = "application/x-www-form-urlencoded"} -Body $body
$token = $response.access_token
Get Extensions device
$apiUrl = 'https://graph.microsoft.com/v1.0/devices/<ID-Object>/extensions' ## change <ID-Object> for your ObjectID.
(https://learn.microsoft.com/en-us/graph/api/device-get?view=graph-rest-1.0&tabs=cs)
$Data = Invoke-RestMethod -Headers #{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Get
$Data.Value | fl
Add extensions device
$apiUrl = 'https://graph.microsoft.com/v1.0/devices/<ID-Object>/extensions'
$body = '{
"#odata.type": "microsoft.graph.openTypeExtension",
"id": "test.extension",
"name_extension": "example"
}'
Invoke-RestMethod -Headers #{Authorization = "Bearer $token"; "Content-type" = "application/json"} -Uri $apiUrl -Method Post -Body $body
Update extensions device
## Actualizar datos de una extensión
$apiUrl = 'https://graph.microsoft.com/v1.0/devices/<ID-Object>/extensions/test.extension' ## Extension ID to update
$body = '{
"#odata.type": "microsoft.graph.openTypeExtension",
"id": "test.extension",
"name_extension": "new_value"
}'
Invoke-RestMethod -Headers #{Authorization = "Bearer $token"; "Content-type" = "application/json"} -Uri $apiUrl -Method Patch -Body $body
Delete extensions device
$apiUrl = 'https://graph.microsoft.com/v1.0/devices/<ID-Object>/extensions/test.extension'
Invoke-RestMethod -Headers #{Authorization = "Bearer $token"; "Content-type" = "application/json"} -Uri $apiUrl -Method Delete

Assign application to user based on e-mail address

In our school we use the Azure AD. Currently we have two custom applications A and B.
We should assign application A to all the users with mail address *#student.example.com and the users with #example.com to application B.
How can we assign the users based on this criteria without doing in manually?
You can use Graph API to automate this process. Here is a PowerShell Script I wrote to use the Graph API.
Add-Type -Path 'C:\Program Files\Microsoft Azure Active Directory Connect\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
# Some common fields to log into your tenant.
$tenantID = "<your tenantID>"
$loginEndpoint = "https://login.windows.net/"
# The default redirect URI and client id.
# No need to change them.
$redirectURI = New-Object System.Uri ("urn:ietf:wg:oauth:2.0:oob")
$clientID = "1950a258-227b-4e31-a9cf-717495945fc2"
$username = "<a global user of your tenant>"
$email_prefix1 = "*#student.example.com"
$email_prefix2 = "*#example.com"
# The display name of your AD apps, It's better if one does not contain another,
# because I am using the filter "startwith".
$apps1 = "<the display name of you first AD application>"
$apps2 = "<the display name of you second AD application>"
$resource = "https://graph.windows.net/"
# logging into your tenant to get the authorization header.
$authString = $loginEndpoint + $tenantID
$authenticationContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext ($authString, $false)
$promptBehaviour = [Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Auto
$userIdentifierType = [Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifierType]::RequiredDisplayableId
$userIdentifier = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier ($username, $userIdentifierType)
$authenticationResult = $authenticationContext.AcquireToken($resource, $clientID, $redirectURI, $promptBehaviour, $userIdentifier);
# construct authorization header for the REST API.
$authHeader = $authenticationResult.AccessTokenType + " " + $authenticationResult.AccessToken
$headers = #{"Authorization"=$authHeader; "Content-Type"="application/json"}
# getting the service principal object id of the 2 AD apps.
$uri = "https://graph.windows.net/$tenantID/servicePrincipals?api-version=1.5&`$filter=startswith(displayName,'$apps1')"
$apps = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
$app1_objectId = $apps.value[0].objectId
$uri = "https://graph.windows.net/$tenantID/servicePrincipals?api-version=1.5&`$filter=startswith(displayName,'$apps2')"
$apps = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
$app2_objectId = $apps.value[0].objectId
# getting the users in the tenant.
$uri = "https://graph.windows.net/$tenantID/users?api-version=1.5"
$users = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
# loop through the whole user list to assign the AD apps.
foreach ($user in $users.value){
$userID = $user.objectId
if ($user.otherMails[0] -like $email_prefix1){
$resourceId = $app1_objectId
}
elseif ($user.otherMails[0] -like $email_prefix2){
$resourceId = $app2_objectId
}
else{
continue
}
# Leave the id to be 00000000-0000-0000-0000-000000000000.
# This is exactly how Azure Classic Portal handles user assigning.
# That means if you assign a user to an AD application in the portal,
# the appRoleAssignment will have the id 00000000-0000-0000-0000-000000000000.
$body = #"
{"id": "00000000-0000-0000-0000-000000000000",
"principalId": "$userID",
"resourceId": "$resourceId"
}
"#
$uri = "https://graph.windows.net/$tenantID/users/$userID/appRoleAssignments?api-version=1.5"
Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Body $body
}
Notice that I am using the email address in otherMails. If you are using Live id, that email address is just the user's live id. If you are using organization id, you can have it set in the classic portal as field Alternate email address.

Resources