im trying to write a backend program that will get all of Azure Security Center tasks (Recommendation) with no browser authorization involved.
As far as i saw, Graph API does not have an end point for Security tasks and the only endpoint i could find is https://learn.microsoft.com/en-us/rest/api/securitycenter/tasks/list which supports only Implicit flow authorization.
Is there a way to get authorization without using consent window in the browser, or to get the tasks via different endpoint?
You can use the below Powershell script which is using the REST API to get all the tasks:
$subscriptionId = "yoursubid"
$context = Get-AzContext
$profile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
$profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($profile)
$token = $profileClient.AcquireAccessToken($context.Subscription.TenantId)
$authHeader = #{
'Content-Type' = 'application/json'
'Authorization' = 'Bearer ' + $token.AccessToken
}
$uri = "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.Security/tasks?api-version=2015-06-01-preview"
$response = Invoke-RestMethod -Uri $uri `
-Method Get `
-Headers $authHeader
$response.value | ConvertTo-Json
OR
You can directly use Azure CLI to get directly .
Command:
az security task list
Reference:
az security task | Microsoft Docs
Install the Azure Az PowerShell module with PowerShellGet | Microsoft Docs
Output for the above powershell script:
For those who will need this in the future,
it is possible.
It didnt work for me because i requested the bearer token from the wrong address, use the following url for the bearer token request:
https://login.microsoftonline.com/{tenantId}/oauth2/token
And NOT:
https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token
(This is the azure AD typical bearer token request url)
If you would rather not mess around with getting the bearer token (and you want to go the powershell route) you can also use Invoke-AzRestMethod
# Capture everything MDC can do from a REST API
$Capabilities = (Invoke-AzRestMethod -ApiVersion "2022-09-01" -ResourceProviderName 'Microsoft.Security').Content | ConvertFrom-Json
$Capabilities.resourceTypes
Related
Two apps registered in two different tenants with identical Microsoft graph permission.
All I am trying to use Powershell Invoke-RestMethod with Micorsoft Graph API. Same code, works for one but not the other one.
Any Idea why?
Not sure what to try. Access token gets created. App authentication message also prints on the screen (both cases)
Click here for the picture of the full permission
I tried to reproduce the same in my environment and got the same error as below.
To resolve this issue, check whether you have granted admin consent like below.
After adding admin consent, use the below code to get token.
$tenantId = <tenantID>
$applicationId = <appID>
$secret= <secret>
$param = #{
Uri = "https://login.microsoftonline.com/$tenantId/oauth2/token?
api-version=2020-06-01";
Method = 'Post';
Body = #{
grant_type = 'client_credentials';
resource =
'https://graph.microsoft.com';
client_id = $applicationId;
client_secret = $secret
}
}
$result = Invoke-RestMethod #param
$token = $result.access_token
You can change the Uri based on your requirement and run the below commands.
$authHeader= #{Authorization=("Bearer {0}" -f $token)}
Invoke-RestMethod -Uri https://graph.microsoft.com/v1.0/users -Method GET -Headers $authHeader
Result:
Scenario: I'm trying to get an access token using a web request as I cannot use Azure PowerShell. The situation I'm trying to replicate is Get-AzAccessToken, where I've authenticated using my username and password and I'm not supplying a client_id.
I can get an access token in PowerShell using the following:
$postParams = #{
grant_type = 'password'
client_id = $ClientId
username = $Username
password = $Password
scope = 'https://graph.microsoft.com/.default'
}
Write-Host "Getting access token for app"
Invoke-RestMethod `
-Uri https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token `
-Method POST `
-ContentType application/x-www-form-urlencoded `
-Body $postParams
I can also get an access token by using the Azure PowerShell command Get-AzAccessToken.
Is it possible to get an access token without using a client_id? If not, is Get-AzAccessToken using a client_id?
It is not possible without a client id. And yes, Azure PowerShell is using one. The best way to implement this is to register your own app and use its client id.
I am working on automating Azure Active Directory App Registrations and Azure Devops Service Connections, and have hit a wall.
I want to query Azure DevOps service connections (service endpoints) by Service Principal ID (or at least get the id). This is possible when using Azure CLI:
az devops service-endpoint list --query "[?authorization.parameters.serviceprincipalid=='xxx']"
But since I am running this in Azure automation account as a powershell runbook, the Azure CLI is not supported.
Then I tried the Azure DevOps REST API, and called it from powershell, but the response does not contain the service principal ID, but just this:
authorization : #{parameters=; scheme=ServicePrincipal}
Does anyone have an idea on how to solve this?
UPDATE
I am calling the rest API like this:
$uriAccount = $UriOrg + "_apis/serviceendpoint/endpoints?endpointNames={name}&api-version=6.1-preview.4"
$result = Invoke-RestMethod -Uri $uriAccount -Method get -Headers $AzureDevOpsAuthenicationHeader
And $result.value gives me this:
authorization : #{parameters=; scheme=ServicePrincipal}
You can try the REST API Endpoints - Get Service Endpoints By Names.
GET https://dev.azure.com/{organization}/{project}/_apis/serviceendpoint/endpoints?endpointNames={endpointNames}&api-version=6.0-preview.4
In this REST API, you can find the id and details by the name of a service connection.
Here is an example to use the REST API in PowerShell:
$token = "{pat}"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$url="https://dev.azure.com/{organization}/{project}/_apis/serviceendpoint/endpoints?endpointNames={endpointNames}&api-version=6.0-preview.4"
$head = #{ Authorization =" Basic $token" }
Invoke-RestMethod -Uri $url -Method GET -Headers $head
Update:
The cause for this question is that you output result in the wrong way.
For JSON response bodies, there is no intuitive way to get results without specifying the final layer.
Here is my modified code, notice how I print result:
$token = "{pat}"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$url="https://dev.azure.com/{organization}/{project}/_apis/serviceendpoint/endpoints?endpointNames={endpointNames}&api-version=6.0-preview.4"
$head = #{ Authorization =" Basic $token" }
$reslut = Invoke-RestMethod -Uri $url -Method GET -Headers $head
echo $result.value.authorization.parameters
I'm new to Azure and powershell. I have some very basic knowledge of both and some scripting experience but not in powershell.
Goal : Get list of applications from Azure and all available associated information. Specifically creationdate. Output in CSV.. Applications created in the last 60 days
and https://learn.microsoft.com/en-us/powershell/module/azurerm.resources/get-azurermadapplication?view=azurermps-6.13.0 this I havent got to work at all but seems like what I want.
$ClientID = "XCXXXXXXXXXXXXXXXX"
$ClientSecret = "XCXXXXXXXXXXXXXXXX"
$tenantdomain = "XCXXXXXXXXXXXXXXXX"
$loginURL = "XCXXXXXXXXXXXXXXXX"
$resource = "https://graph.microsoft.com"
$path = "C:\Scripts\objects.csv"
$headers = "App Name,CreatedOn"
# body for the rest request to get an access token
$body = #{grant_type="client_credentials";resource=$resource;client_id=$ClientID;client_secret=$ClientSecret}
# get an access token
$oauth = Invoke-RestMethod -Method Post -Uri $loginURL/$tenantdomain/oauth2/token?api-version=1.0 -Body $body
# if we have an access token, then make the graph call
if ($oauth.access_token -ne $null)
{
$headerParams = #{'Authorization'="$($oauth.token_type) $($oauth.access_token)"}
$url = "https://graph.microsoft.com/beta/applications?select=createddatetime,displayname"
do {
$response = Invoke-WebRequest -Uri $url -UseBasicParsing -Headers $headerParams -Method GET -ContentType "application/json"
if ($response.Content)
{
The old AzureRm powershell Get-AzureRmADApplication you mentioned essentially calls the azure ad graph api, in azure ad graph api, the application entity does not have the createddatetime property which you want. Besides, the new Az powershell Get-AzADApplication and azure ad powershell Get-AzureADApplication also call the azure ad graph API, so they could not meet your requirement.
Your script is a workaround, the script uses the client credential flow to get the access token and uses the token to call the Microsoft graph API, the logic should be correct.
Due to you did not provide some error information about your script, I could just give you a sample, it works fine on my side.
First, before you get the access token, make sure you have granted the Microsoft graph API permission for your ad app. Navigate to the Azure Active Directory in the portal -> App registrations -> find your ad app -> API permissions -> Add a permission -> add the Application permission of Microsoft graph api(the permission could be Application.ReadWrite.All, Directory.Read.All from least to most privileged, see List applications Permissions) -> Add permissions -> At last, don't forget to click the Grant admin consent button.
My sample(the sample is after getting the access token and use it to call MS garph api):
$url = "https://graph.microsoft.com/beta/applications?select=createddatetime,displayname"
$accesstoken = "eyJ0eXAxxxxxxeHB1Y3FuQktJR2Nyx9Cg"
$header = #{
'Authorization' = 'Bearer ' + $accesstoken
}
$response = Invoke-RestMethod –Uri $url –Headers $header –Method GET
$response.value | Export-Csv -Path "C:\Users\joyw\Desktop\testfile.csv" -NoTypeInformation
How to get the access token to start or shut down VMs on azure classic portal, I have tried multiple links for the same such as https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-api-authentication, also whatever access token I m getting using that I can only start, shutdown ARM vms, not classic VMs. Can somebody please help me on this ?
I'm very lazy, so I'm using arm token to startup\shutdown classic vms :). sample code:
$header = #{ Authorization = "Bearer $token" }
$uri = "https://management.azure.com{0}/{1}?api-version={2}" -f $vmId, $action, $apiVer
Invoke-WebRequest -Headers $header -Method Post -Uri $uri -UseBasicParsing
to start use $action = 'start'
to shutdown use $action = 'shutdown'
for apiVersion use $apiVer = '2017-04-01'
for ID, just use classic VM resource id, example:
/subscriptions/GUID/resourceGroups/rgName/providers/Microsoft.ClassicCompute/virtualMachines/vmName
you would need to grant yourself (or the entity you are getting script on behalf of) proper rights. I'm using these:
"Microsoft.ClassicCompute/virtualMachines/read"
"Microsoft.ClassicCompute/virtualMachines/start/action"
"Microsoft.ClassicCompute/virtualMachines/shutdown/action"
"Microsoft.ClassicCompute/virtualMachines/operationStatuses/read"