Defender 365 REST API (you don't have any of the required app permissions (Incident.ReadWrite.All, Incident.Read.All) to access resource) - azure

I am trying to download list of incidents from Defender 365 (MDATP).
I have a script to get a Bearer Token:
. 'Functions\Credentials.ps1'
Function GET_BEARER_TOKEN_FOR_MDATP_AUTHENTICATION {
$Body = [Ordered] #{
resource = "$ResourceApplicationIdUri"
client_id = "$ApplicationId"
client_secret = "$ApplicationSecret"
grant_type = 'client_credentials'
}
try {
$Response = Invoke-RestMethod -Method Post -Uri $OAuthenticationURI -Body $body -ErrorAction Stop
}
catch {
Write-Output("unable to get the bearer token")
Exit
}
$BearerToken = $Response.access_token
return $BearerToken
}
$xx = GET_BEARER_TOKEN_FOR_MDATP_AUTHENTICATION
$xx | Out-File '.\Bearer_Token.txt'
That script worked fine. Today, I have been granted permission to display incidents.
When I try to do that, I get the error message:
{
"error": {
"code": "Forbidden",
"message": "The application does not have any of the required application permissions (Incident.ReadWrite.All, Incident.Read.All) to access the resource.",
}
}
When I check in the token tester website: https://jwt.ms/
I cannot see those incident.Read.All Roles but only:
"roles": [
"Alert.ReadWrite.All",
"AdvancedQuery.Read.All"
]
Roles have been given by this instruction manual:
https://learn.microsoft.com/en-us/microsoft-365/security/defender/api-create-app-web?view=o365-worldwide
Many Thanks,
Aster

so I have found the issue:
$ResourceApplicationIdUri = 'https://api.securitycenter.microsoft.com' (Alerts are allowed)
$ResourceApplicationIdUri = 'https://api.security.microsoft.com' (Incidents are allowed)
Regards,
Aster

Related

Azure Log Analytics purge requests failing with Internal Server Error

I am trying to purge few records from an Azure Log Analytics workspace table.
I am following the documentation from https://learn.microsoft.com/en-us/rest/api/loganalytics/workspace-purge/purge
My account has Data Purger RBAC role added. Also, I am an Owner on the subscription.
I have tried the Try it button on the documentation page, but get Internal Server error after triggering the HTTP post request.
Request Body/Payload
{
filters: [
{
"column": "TimeGenerated",
"operator": ">",
"value": "2022-05-26T06:09:00"
}],
table: "AppRequests"
}
error response
{
"error": {
"code": "InternalServerError",
"message": "Operation Id: 1df0f52bd248b548b713baf53288eec6"
}
}
I have also coded a PowerShell script and tried but getting the same error my script:
param(
[Parameter(Mandatory = $true)][string]$SubscriptionName,
[Parameter(Mandatory = $true)][string]$ResourceGroupName,
[Parameter(Mandatory = $true)][string]$WorkspaceName
)
Set-AzContext -Subscription $SubscriptionName | Out-Null
$AzContext = Get-AzContext
$AzAccessToken = Get-AzAccessToken -TenantId $AzContext.Tenant.Id
$Token = $AzAccessToken.Token
$SubscriptionId = $AzContext.Subscription.Id
$LogAnalyticsPurgeUriBase = "https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroupName/providers/Microsoft.OperationalInsights/workspaces/$WorkspaceName/purge?api-version=2020-08-01";
Write-Host $LogAnalyticsPurgeUriBase
$AuthHeader = #{
'Content-Type' = 'application/json'
'Authorization' = "Bearer $Token"
}
Write-Host $AuthHeader
$Body = #"
{
"table": "AppRequests",
"filters": [
{
"column": "TimeGenerated",
"operator": ">",
"value": "2022-05-26T06:09:00"
}]
}
"#
Write-Host $Body
$PurgeResult = Invoke-RestMethod -Method Post -Uri $LogAnalyticsPurgeUriBase -Body $Body -Headers $AuthHeader
Return $PurgeResult;
error response after executing the PowerShell script ( and passing the parameters )
{"error":{"code":"InternalServerError","message":"Operation Id: 4159055a9a69bb44afd3509c3a2d42ca"}}
I have gone to the Log Analytics activity log - events pane and tried getting more details on the error there, but unfortunately the events details there also just mention 'Internal Server' error without expanding any details.
Any guidance on what I am doing wrong would be much appreciated. Thank you!
Issue is unrelated to anything you performed (No client-side error is visible in the response). it originates from the RP (Azure Resource provider), 500 is a server-side error, hence - they will need to address it. if you have the option to open a ticket with their support that will be recommended as next move.

How to manage the Azure APIM developer portal delegation with Azure PowerShell

I want to enable the Azure APIM developer portal sign-in & sign-up delegation and to generate a "Delegation Validation Key". This is straightforward with the Azure portal:
I want to achieve the same thing but with Azure PowerShell as part of a bigger deployment pipeline.
I cannot find any documentation on how to do that.
Thanks
AFAIK, We can not achieve the above requirement using powershell , Here are the details (MICROSOFT DOCUMENTATION) for what we can configure through powershell for APIM .
Instead of that we can configure the above requirement using git , Please refer this MICRSOFT DOCUMENTATION for more details & the list of cmdlets for APIM .
An additional option is to use an HTTP call against the resource. The call can be made with the PowerShell script as well.
This can be done as follows:
Get an Azure access token - you should have a Service Principal with sufficient permissions for the resource we are going to deal with.
$tokenUri = "https://login.microsoftonline.com/${tenantId}/oauth2/token"
$form = #{
grant_type = 'client_credentials'
resource = 'https://management.core.windows.net/'
client_id = $spClientId
client_secret = $spClientSecret
}
$response = Invoke-RestMethod -Uri $tokenUri -Method Post -Body $form
$azureToken = $response.access_token
Send an HTTP request against the APIM service
$url = "https://management.azure.com/subscriptions/${subscriptionId}/resourceGroups/${apiManagementRg}/providers/Microsoft.ApiManagement/service/${apiManagementName}/portalsettings/delegation?api-version=2020-12-01"
$headers = #{ 'Authorization' = "Bearer ${azureToken}" }
$body = #"
{
"properties": {
"url": "$delegationUrl",
"validationKey": "$validationKey",
"subscriptions": {
"enabled": false
},
"userRegistration": {
"enabled": true
}
}
}
"#
$delegationResponse = Invoke-RestMethod -Method 'Put' -Body $body -Uri $url -Headers $headers

Microsoft Graph API Get Group Events

I'm trying to use the MS Graph API (which I'm new at) to write a Powershell script to copy the events from a private group calendar into a public group calendar.
So far I've managed to get the private group using this call:
$api = "https://graph.microsoft.com/v1.0/groups"
$groups = $null
try { $groups = Invoke-RestMethod -Headers #{Authorization = "Bearer $($token.access_token)" } -Uri $api -Method "GET" -ContentType "application/json" }
catch { Write-host -Foreground Red $_}
$calendar_group = $groups.value | ? -Property mailNickname -eq $pvt_group
However, when I try and move this forth and get the events for that group, I get bounced on a 403 error.
The calls I'm trying are either:
$api = "https://graph.microsoft.com/v1.0/groups/$group_ID/calendar/events"
Write-Host $api -Fore Green
$events = $null
try { $events = Invoke-RestMethod -Headers #{Authorization = "Bearer $($token.access_token)" } -Uri $api -Method "GET" -ContentType "application/json" }
catch { Write-host -Foreground Red $_}
Or:
$api = "https://graph.microsoft.com/v1.0/groups/$group_ID/events"
Write-Host $api -Fore Green
$events = $null
try { $events = Invoke-RestMethod -Headers #{Authorization = "Bearer $($token.access_token)" } -Uri $api -Method "GET" -ContentType "application/json" }
catch { Write-host -Foreground Red $_}
Both fail on the same error.
NB: the $group_ID variable is correctly valued by the first call.
I've the app registered on Azure with the following permimssions:
Calendars.Read Delegated
Calendars.Read.Shared Delegated
Calendars.ReadWrite Delegated
Calendars.ReadWrite.Shared Delegated
Directory.AccessAsUser.All Delegated
Directory.Read.All Delegated
Directory.Read.All Application
Directory.ReadWrite.All Delegated
Directory.ReadWrite.All Application
Group.Read.All Delegated
Group.Read.All Application
Group.ReadWrite.All Delegated
Group.ReadWrite.All Application
GroupMember.Read.All Delegated
GroupMember.Read.All Application
User.Read Delegated
Does anybody know what I'm doing wrong?
Many thanks in advance.
The access token that you use, is an application access token (the permissions are defined under the Roles section). If a user access token is used, you will see the permissions under de scp section.
In the Microsoft docs (here) it is stated that calling the /calendar/events unfortunately is not supported with an application access token.
If you assign your account to the Groups administrator role, you will implicitly be assigned the Group.Read.All permission. Then use the access token from your account to call the endpoint without any issues (because you've already granted the needed permissions for delegation in the App Registration).

Access token validation failure for AD graph API after using the token acquired from AzureRmContext in Powershell

I am trying to make API calls to Microsoft graph API using Oauth2 to log in.
I tried to use AzureRm cmdlet to get the token for my account, so I can make the API calls, but the message "Access token validation failure. Invalid audience." showed up in the JSON response.
Login-AzureRmAccount
$currentAzureContext = Get-AzureRmContext
$tenantId = $currentAzureContext.Tenant.Id
$accountId = $currentAzureContext.Account.Id
$tokenCache = $currentAzureContext.TokenCache
$cachedTokens = $tokenCache.ReadItems() `
| where { $_.TenantId -eq $tenantId }
$accessToken = $cachedTokens.AccessToken
Invoke-RestMethod -Method Get `
-Uri ("https://graph.microsoft.com/v1.0/me") `
-Headers #{ "Authorization" = "Bearer " + $accessToken }
The following is the JSON response:
Invoke-RestMethod : {
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure. Invalid audience.",
"innerError": {
"request-id": "8429e520-401b-4382-adad-4f55bccbe752",
"date": "2019-11-04T16:53:27"
}
}
}
Have a look at the token in https://jwt.ms and see what is the aud claim. I think the token you get via AzureRm is an access token to the Azure Management APIs. The value for MS Graph is 'https://graph.microsoft.com'. You can use the AzureAD PS module to get Graph tokens. Also note that AAD is notthe same as MS Graph.

Azure DevOps REST API returns a 403 when using the system OAuth token during a build

I'm running a script:
# Variables
$organization = "****"
$project = "****"
$repositoryId = "****"
$pullRequestId = $env:BUILD_PULLREQUEST_ID
$pat = "Bearer $env:System_AccessToken"
$featureReleaseUrl = "http://" + $env:prSourceBranchName + ".azurewebsites.net"
$body = #"
{
"comments": [
{
"content": "Link naar feature release $featureReleaseUrl"
}
]
}
"#
$createThreadInPRUrl = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repositoryId/pullRequests/$pullRequestId/threads?api-version=5.0"
if ($pullRequestId) {
Invoke-RestMethod -Uri $createThreadInPRUrl -Headers #{Authorization = $pat} -Body $body -Method Post -ContentType 'application/json'
}
When it runs it returns a:
##[error]The remote server returned an error: (403) Forbidden.
I've created a Personal Access Tokens in my personal settings.
I've also created this script:
# Variables
$organization = "****"
$project = "****"
$buildId = $****
$pat = "Bearer $env:System_AccessToken"
if (!$env:Build_PullRequest_SourceBranchName) {
$retrieveSourceBranchFromBuildURL = "https://dev.azure.com/$organization/$project/_apis/build/builds/$buildId" + "?api-version=5.0"
$buildInformation = Invoke-RestMethod -Uri $retrieveSourceBranchFromBuildURL -Headers #{Authorization = $pat } -Method Get -ContentType 'application/json'
$SourceBranchFromBuild = $buildInformation.sourceBranch.split('/')[-1]
Write-Host "### no Build PullRequest SourceBranchName available ###"
Write-Host "##vso[task.setvariable variable=prSourceBranchName;]"$SourceBranchFromBuild
}
And this runs fine. The difference between the first and second script is that the first is a POST and the second a GET. But they both use the $pat token.
Even though the token you used is System.AccessToken, if you don't have access permission of Pull Request, you will also could not operate it.
Go Project Setting--> Repositories--> Repository you want to access, locate your account or the group you are in. Check the permission state of Contribute to pull requests.
You must have this Contribute to pull requests permission allowed, so that you can add the comment to PR.

Resources