Issue with Automation Accounts>Runbooks: The remote server returned an error: (401) Unauthorized - azure

I am facing on an issue with azure script. I created a runbook in automation accounts and I gave to new app the contributor rights on subscription, but when I run the code I see:
The remote server returned an error: (401) Unauthorized. Invoke-WebRequest : The remote server returned an error: (401) Unauthorized. At line:82 char:13 + $All_BSOD = Invoke-WebRequest -Uri $Top50_BSOD_URL -Method GET -Heade ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand .
At below there are the code:
# Function to send Teams notif
Function Send_Notif
{
param(
$Text,
$Title
)
$Body = #{
'text'= $Text
'Title'= $Title
'themeColor'= "$Color"
}
$Params = #{
Headers = #{'accept'='application/json'}
Body = $Body | ConvertTo-Json
Method = 'Post'
URI = $Webhook_URL
}
Invoke-RestMethod #Params
}
#*****************************************************************
# Part to fill
#*****************************************************************
# Teams webhoot link
$Webhook_URL = "personal link"
# Choose the top x devices (default is 50)
$Top_count = 50
# Teams notif design
$Notif_Title = "Top 50 devices with BSOD"
$Notif_Message = "Here is the list of top 50 devices with BSOD on the last 30 days"
$Color = "2874A6"
#*****************************************************************
# Getting a token
$url = $env:IDENTITY_ENDPOINT
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("X-IDENTITY-HEADER", $env:IDENTITY_HEADER)
$headers.Add("Metadata", "True")
$body = #{resource='https://graph.microsoft.com/' }
$script:accessToken = (Invoke-RestMethod $url -Method 'POST' -Headers $headers -ContentType 'application/x-www-form-urlencoded' -Body $body ).access_token
# Authentication
Connect-AzAccount -Identity
$headers = #{'Authorization'="Bearer " + $accessToken}
# Graph URL to use
$Top50_BSOD_URL = "https://graph.microsoft.com/beta/deviceManagement/userExperienceAnalyticsDevicePerformance?dtFilter=all&`$orderBy=blueScreenCount%20desc&`$top=$Top_count&`$filter=blueScreenCount%20ge%201%20and%20blueScreenCount%20le%2050"
$StartupHistory_url = "https://graph.microsoft.com/beta/deviceManagement/userExperienceAnalyticsDeviceStartupHistory?" + '$filter=deviceId%20eq%20%27' + "$DeviceID%27"
# Getting BSOD info
$All_BSOD = Invoke-WebRequest -Uri $Top50_BSOD_URL -Method GET -Headers $Headers -UseBasicParsing
$All_BSOD_JsonResponse = ($All_BSOD.Content | ConvertFrom-Json)
$Get_All_BSOD = $All_BSOD_JsonResponse.value
$BSOD_Array = #()
ForEach($BSOD in $Get_All_BSOD)
{
$Device_Model = $BSOD.model
$Device_Name = $BSOD.deviceName
$BSOD_Count = $BSOD.blueScreenCount
$DeviceID = $BSOD.id
$Get_StartupHistory = Invoke-WebRequest -Uri $StartupHistory_url -Method GET -Headers $Headers -UseBasicParsing
$Get_BSOD_JsonResponse = ($Get_StartupHistory.Content | ConvertFrom-Json)
$Get_BSOD = ($Get_BSOD_JsonResponse.value | Where {$_.restartCategory -eq "blueScreen"})[-1]
$Last_BSOD_Date = [datetime]($Get_BSOD.startTime)
$Last_BSOD_Code = $Get_BSOD.restartStopCode
$OS = $Get_BSOD.operatingSystemVersion
$BSOD_Obj = New-Object PSObject
Add-Member -InputObject $BSOD_Obj -MemberType NoteProperty -Name "Device" -Value $Device_Name
Add-Member -InputObject $BSOD_Obj -MemberType NoteProperty -Name "Model" -Value $Device_Model
Add-Member -InputObject $BSOD_Obj -MemberType NoteProperty -Name "Count" -Value $BSOD_Count
Add-Member -InputObject $BSOD_Obj -MemberType NoteProperty -Name "OS version" -Value $OS
Add-Member -InputObject $BSOD_Obj -MemberType NoteProperty -Name "Last BSOD" -Value $Last_BSOD_Date
Add-Member -InputObject $BSOD_Obj -MemberType NoteProperty -Name "Last code" -Value $Last_BSOD_Code
$BSOD_Array += $BSOD_Obj
}
$BSOD_Table = $BSOD_Array | ConvertTo-HTML -Fragment
$BSOD_Table = $BSOD_Table.Replace("<table>","<table border='1'>")
$Text_Message = "$Notif_Message<br><br>
$BSOD_Table
"
Send_Notif -Text $Text_Message -Title $Notif_Title | out-null
Anybody can help me?
thank you
PS: this is the original webpage text
My aim is to get a notification to all bsod\devices in my enviroment

Related

Assigning Intune scope tags to Azure Azure AD group

I cannot figure this on out. I need a way to assign Endpoint Manager's Scope tags to an Azure AD group using Microsoft Graph and PowerShell.
Under the portal this is done under Endpoint Manager\Tenant Administration\Roles\Scope (Tags). Then clicking on the Tag and tgo to assignments and browse to Azure AD group.
Since its under Roles, I'm assuming it falls under the roleAssignment or roleScopeTag resource types?
I have thoroughly read all documentation for the REST api and I have also attempted to do this via Microsoft.Graph.Intune modules but still cannot find a suitable cmdlet that will do this. Am I missing something?
Here is the current code I have built following this document
FIRST let's assume I have the correct tag id and azure ad group object id.
$ScopeTagId = 2
$TargetGroupIds = #()
$TargetGroupIds += '687c08f1-e78f-4506-b4a6-dfe35a05d138'
$graphApiVersion = "beta"
$Resource = "deviceManagement/roleScopeTags"
$object = New-Object -TypeName PSObject
$object | Add-Member -MemberType NoteProperty -Name 'assignments' -Value #($TargetGroupIds)
$JSON = $object | ConvertTo-Json
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)/$ScopeTagId/assign"
Invoke-RestMethod -Method Post -Uri $uri -Headers $global:authToken -Body $JSON
No success. I then thought that since the create roleScopeTag API doesn't have an assignment property in the request body, this must be done using the update method, but that doesn't have it in there either. The only one I read was to use the assign action and in the documentation example it shows the roleScopeTagAutoAssignment URI, so I went down that rabbit hole:
$ScopeTagId = 2
$TargetGroupIds = #()
$TargetGroupIds += '687c08f1-e78f-4506-b4a6-dfe35a05d138'
$graphApiVersion = "beta"
$Resource = "deviceManagement/roleScopeTags"
$AutoTagObject = #()
foreach ($TargetGroupId in $TargetGroupIds) {
#Build custom object for assignment
$AssignmentProperties = "" | Select '#odata.type',id,target
$AssignmentProperties.'#odata.type' = '#microsoft.graph.roleScopeTagAutoAssignment'
$AssignmentProperties.id = $TargetGroupId
#Build custom object for target
$targetProperties = "" | Select "#odata.type",deviceAndAppManagementAssignmentFilterId,deviceAndAppManagementAssignmentFilterType
$targetProperties."#odata.type" = "microsoft.graph.deviceAndAppManagementAssignmentTarget"
$targetProperties.deviceAndAppManagementAssignmentFilterId = $TargetGroupId
$targetProperties.deviceAndAppManagementAssignmentFilterType = 'include'
#add target object to assignment
$AssignmentProperties.target = $targetProperties
$AutoTagObject += $AssignmentProperties
}
#build body object
$object = New-Object -TypeName PSObject
$object | Add-Member -MemberType NoteProperty -Name 'assignments' -Value #($AutoTagObject)
$JSON = $object | ConvertTo-Json
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)/$ScopeTagId/assign"
Invoke-RestMethod -Method Post -Uri $uri -Headers $global:authToken -Body $JSON
The error I get back is something like: "Property target in payload has a value that does not match schema.","innerError":{"date":"2022-01-27T16:28:34","request-id":"75626c4d-f09b-438e-8b0f-0b2928ac23ce","client-request-id":"75626c4d-f09b-438e-8b0f-0b2928ac23ce" which I assume is the odata.type object i'm calling "microsoft.graph.deviceAndAppManagementAssignmentTarget"
There is a second post method in the documentations via roledefinition URI which seems like an unnecessary step, but I tried that too with no success.
I do not know if any of this is correct. I understand the API calls for others pretty well and I have been able to successfully add Tags for Custom Roles and their assignments using graph; I just can't seem to find the right combination of URI and JSON body for scope tags themselves...if it even exists. :(
Any ideas, please share some code snippets if you can. THANKS!
I found the correct URI and request body
If can be generated like this:
$ScopeTagId = 2
$TargetGroupIds = #()
$TargetGroupIds += '687c08f1-e78f-4506-b4a6-dfe35a05d138'
$graphApiVersion = "beta"
$Resource = "deviceManagement/roleScopeTags"
$AutoTagObject = #()
#TEST $TargetGroupId = $TargetGroupIds[0]
foreach ($TargetGroupId in $TargetGroupIds) {
#Build custom object for assignment
$AssignmentProperties = "" | Select id,target
$AssignmentProperties.id = ($TargetGroupId + '_' + $ScopeTagId)
#Build custom object for target
$targetProperties = "" | Select "#odata.type",deviceAndAppManagementAssignmentFilterId,deviceAndAppManagementAssignmentFilterType,groupId
$targetProperties."#odata.type" = "microsoft.graph.groupAssignmentTarget"
$targetProperties.deviceAndAppManagementAssignmentFilterId = $null
$targetProperties.deviceAndAppManagementAssignmentFilterType = 'none'
$targetProperties.groupId = $TargetGroupId
#add target object to assignment
$AssignmentProperties.target = $targetProperties
$AutoTagObject += $AssignmentProperties
}
#build body object
$object = New-Object -TypeName PSObject
$object | Add-Member -MemberType NoteProperty -Name 'assignments' -Value #($AutoTagObject)
$JSON = $object | ConvertTo-Json -Depth 10
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)/$ScopeTagId/assign"
Invoke-RestMethod -Method Post -Uri $uri -Headers $global:authToken -Body $JSON -ErrorAction Stop
The Json request body would look like this:
{
"assignments": [
{
"id": "b25c80e3-78cc-4b7c-888e-fc50dcc6b582_2",
"target": {
"#odata.type": "microsoft.graph.groupAssignmentTarget",
"deviceAndAppManagementAssignmentFilterId": null,
"deviceAndAppManagementAssignmentFilterType": "none",
"groupId": "b25c80e3-78cc-4b7c-888e-fc50dcc6b582"
}
}
]
}
Nowhere is this documented...

Issue Creating SSL/TLS secure channel

The below given PowerShell Script Basically Checks for Backup Jobs inside Backup Vault and Sends a daily backup job report to emails mentioned. I am Facing issues as the script throws an error
Invoke-RestMethod : The request was aborted: Could not create SSL/TLS secure channel
I am using SendGrid Api Key in a Kv used for the mailing service. Have tried adding an updated TLS Version too it still throws the same error.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Remove-Variable -Name * -ErrorAction SilentlyContinue
$numberofdays = 2
$DAILYBACKUPSTATS = #()
$DAILYBACKUPSTATS1 = #()
$DAILYBACKUPSTATSFAILED = #()
$DAILYBACKUPSTATSFAILED1 = #()
$Subscriptions = Get-AzSubscription
$SubscriptionIDs = $Subscriptions.ID
foreach ($SubscriptionID in $SubscriptionIDs) {
$Subscription = Set-AzContext -SubscriptionId $SubscriptionID
$backupvaults = Get-AzRecoveryServicesVault
$backupvaultnames = $backupvaults.name
foreach ($backupvaultname in $backupvaultnames)
{
$backupvault = Get-AzRecoveryServicesVault -Name $backupvaultname
$startdate = [system.Datetime]::UtcNow
$enddate = ([system.Datetime]::UtcNow).AddDays(1)
for ( $i = 1; $i -le $numberofdays; $i++ ) {
# We query one day at a time
$dailyjoblist = Get-AzRecoveryServicesBackupJob -VaultId $backupvault.ID -From $startdate -To $enddate -Operation Backup;
foreach ( $job in $dailyjoblist ) {
#Extract the information for the reports
$message.Body
$newstatsobj = New-Object System.Object
$newstatsobj | Add-Member -type NoteProperty -name Subscription -value (Get-AzSubscription -SubscriptionId $SubscriptionID).Name
$newstatsobj | Add-Member -type NoteProperty -name Date -value $job.StartTime
$newstatsobj | Add-Member -type NoteProperty -name RecoveryVaultName -value $backupvaultname
$newstatsobj | Add-Member -type NoteProperty -name VMName -value $job.WorkloadName
$newstatsobj | Add-Member -type NoteProperty -name Duration -value $job.Duration
$newstatsobj | Add-Member -type NoteProperty -name Status -value $job.Status
$details = Get-AzRecoveryServicesBackupJob -VaultId $backupvault.ID -Job $job
$DAILYBACKUPSTATS += $newstatsobj
}
$enddate = $enddate.AddDays(-1)
$startdate = $startdate.AddDays(-1)
#Sets the columns
$a = "<style>"
$a = $a + "BODY{background-color:white;}"
$a = $a + "TABLE{border-width: 3px;border-style: double;border-collapse: collapse;font-family: Calibri;}"
$a = $a + "TH{border-width: 3px;padding: 2px;border-style: double;background-color:SandyBrown;font-family: Calibri;}"
$a = $a + "TD{border-width: 3px;padding: 2px;border-style: double;font-family: Calibri;}"
$a = $a + "</style>"
}
}
}
$DAILYBACKUPSTATS += $DAILYBACKUPSTATS1
$EmailBody = "<table width='70%'><tbody>"
$EmailBody += "<tr>"
$EmailBody += "<td width='100%' colSpan=4><font face='Calibri' color='#003399' size='3'>Azure Recovery Services Vault Backup Job Status<BR>NOTE: Date is UTC<BR><BR>"
$EmailBody += "</tr>"
$EmailBody += "</table>"
$message1 = $DAILYBACKUPSTATS | ConvertTo-Html -Head $a
$EmailBody += $message1
$content = $emailBody
$VaultName = "Parent-kv"
$SENDGRID_API_KEY = (Get-AzKeyVaultSecret -VaultName $VaultName -Name "Sendgrd-api").SecretValue
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer " + $SENDGRID_API_KEY)
$headers.Add("Content-Type", "application/json")
$destEmailAddress = "jon#mail.com"
$fromEmailAddress = "Azure-NoReply#cla.com"
$body = #{
personalizations = #(
#{
to = #(
#{
email = $destEmailAddress
}
)
}
)
from = #{
email = $fromEmailAddress
}
subject = $subject
content = #(
#{
type = "text/html"
value = $content
}
)
}
$bodyJson = $body | ConvertTo-Json -Depth 4
$response = Invoke-RestMethod -Uri https://api.sendgrid.com/v3/mail/send -Method Post -Headers $headers -Body $bodyJson
You can most likely search here for a whole bunch of potential remedies.
The request was aborted: Could not create SSL/TLS secure channel
I would also recommend to:
verify that the credentials ($SENDGRID_API_KEY) is correct.
run a network sniffer to see the SSL handshake and see if there any exceptions.

Azure DB sync logs in log analytics workspace

I have an Azure SQL database sync group that is scheduled to run each hour.
Question:
Can i sent this logs to a log analytics workspace by enabling the diagnostic settings?
If yes, what will be the best way to filter them out?
I can successfully get the logs from powershell, but my end goal here is to create an alert based on the sync logs.
Thanks you in advance!
If you want to send Azure SQL database sync group to a log analytics workspace, you can implement it with HTTP Data Collector API.
For example
$SubscriptionId = "SubscriptionId"
$DS_ResourceGroupName = ""
$DS_ServerName = ""
$DS_DatabaseName = ""
$DS_SyncGroupName = ""
# Replace with your OMS Workspace ID
$CustomerId = "OMSCustomerID"
# Replace with your OMS Primary Key
$SharedKey = "SharedKey"
# Specify the name of the record type that you'll be creating
$LogType = "DataSyncLog"
# Specify a field with the created time for the records
$TimeStampField = "DateValue"
Connect-AzureRmAccount
select-azurermsubscription -SubscriptionId $SubscriptionId
#get log
$endtime =[System.DateTime]::UtcNow
$StartTime = ""
$Logs = Get-AzureRmSqlSyncGroupLog -ResourceGroupName $DS_ResourceGroupName `
-ServerName $DS_ServerName `
-DatabaseName $DS_DatabaseName `
-SyncGroupName $DS_SyncGroupName `
-starttime $StartTime `
-endtime $EndTime;
if ($Logs.Length -gt 0)
{
foreach ($Log in $Logs)
{
$Log | Add-Member -Name "SubscriptionId" -Value $SubscriptionId -MemberType NoteProperty
$Log | Add-Member -Name "ResourceGroupName" -Value $DS_ResourceGroupName -MemberType NoteProperty
$Log | Add-Member -Name "ServerName" -Value $DS_ServerName -MemberType NoteProperty
$Log | Add-Member -Name "HubDatabaseName" -Value $DS_DatabaseName -MemberType NoteProperty
$Log | Add-Member -Name "SyncGroupName" -Value $DS_SyncGroupName -MemberType NoteProperty
#Filter out Successes to Reduce Data Volume to OMS
#Include the 5 commented out line below to enable the filter
#For($i=0; $i -lt $Log.Length; $i++ ) {
# if($Log[$i].LogLevel -eq "Success") {
# $Log[$i] =""
# }
# }
}
$json = ConvertTo-JSON $logs
$result = Post-OMSData -customerId $customerId -sharedKey $sharedKey -body ([System.Text.Encoding]::UTF8.GetBytes($json)) -logType $logType
if ($result -eq 200)
{
Write-Host "Success"
}
if ($result -ne 200)
{
throw
#"
Posting to OMS Failed
Runbook Name: DataSyncOMSIntegration
"#
}
Function Build-Signature ($customerId, $sharedKey, $date, $contentLength, $method, $contentType, $resource)
{
$xHeaders = "x-ms-date:" + $date
$stringToHash = $method + "`n" + $contentLength + "`n" + $contentType + "`n" + $xHeaders + "`n" + $resource
$bytesToHash = [Text.Encoding]::UTF8.GetBytes($stringToHash)
$keyBytes = [Convert]::FromBase64String($sharedKey)
$sha256 = New-Object System.Security.Cryptography.HMACSHA256
$sha256.Key = $keyBytes
$calculatedHash = $sha256.ComputeHash($bytesToHash)
$encodedHash = [Convert]::ToBase64String($calculatedHash)
$authorization = 'SharedKey {0}:{1}' -f $customerId,$encodedHash
return $authorization
}
# Create the function to create and post the request
Function Post-OMSData($customerId, $sharedKey, $body, $logType)
{
$method = "POST"
$contentType = "application/json"
$resource = "/api/logs"
$rfc1123date = [DateTime]::UtcNow.ToString("r")
$contentLength = $body.Length
$signature = Build-Signature `
-customerId $customerId `
-sharedKey $sharedKey `
-date $rfc1123date `
-contentLength $contentLength `
-method $method `
-contentType $contentType `
-resource $resource
$uri = "https://" + $customerId + ".ods.opinsights.azure.com" + $resource + "?api-version=2016-04-01"
$headers = #{
"Authorization" = $signature;
"Log-Type" = $logType;
"x-ms-date" = $rfc1123date;
"time-generated-field" = $TimeStampField;
}
$response = Invoke-WebRequest -Uri $uri -Method $method -ContentType $contentType -Headers $headers -Body $body -UseBasicParsing
return $response.StatusCode
}
After doing that, you can alert vai log search in Azure log analysis. For more detail, please refer to the blog.

Powershell HTTP Post to Service Bus Queue returns 401

Trying to submit a message to a service bus queue I have set up, and keep getting a 401 Unauthorized return.
I've tried configuring the SAS token myself using this method
$ResourceGroupName = 'myResourceGroup'
$NameSpaceName = "serviceBusNameSpace"
$QueueName = "myQueueName"
$PolicyName = "RootManageSharedAccessKey"
$body = "test message"
$Namespace = (Get-AzServiceBusNamespace -ResourceGroupName $ResourceGroupName -Name $namespacename).Name
$key = (Get-AzServiceBusKey -ResourceGroupName $ResourceGroupName -Namespace $namespacename -Name $PolicyName).PrimaryKey
$origin = [DateTime]"1/1/1970 00:00"
$Expiry = (Get-Date).AddMinutes(5)
#compute the token expiration time.
$diff = New-TimeSpan -Start $origin -End $Expiry
$tokenExpirationTime = [Convert]::ToInt32($diff.TotalSeconds)
#Create a new instance of the HMACSHA256 class and set the key to UTF8 for the size of $Key
$hmacsha = New-Object -TypeName System.Security.Cryptography.HMACSHA256
$hmacsha.Key = [Text.Encoding]::UTF8.GetBytes($Key)
$scope = "https://$Namespace.servicebus.windows.net/"
#create the string that will be used when cumputing the hash
$stringToSign = [Web.HttpUtility]::UrlEncode($scope) + "`n" + $tokenExpirationTime
#Compute hash from the HMACSHA256 instance we created above using the size of the UTF8 string above.
$hash = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($stringToSign))
#Convert the hash to base 64 string
$signature = [Convert]::ToBase64String($hash)
$fullResourceURI = "https://$Namespace.servicebus.windows.net/$QueueName"
#create the token
$token = [string]::Format([Globalization.CultureInfo]::InvariantCulture, `
"SharedAccessSignature sr={0}sig={1}&se={2}&skn={3}", `
[Web.HttpUtility]::UrlEncode($fullResourceURI), `
[Web.HttpUtility]::UrlEncode($signature), `
$tokenExpirationTime, $PolicyName)
$headers = #{ "Authorization" = "$token"; "Content-Type" = "application/atom+xml;type=entry;charset=utf-8" }
$uri = "https://$Namespace.servicebus.windows.net/$QueueName/messages"
$headers.Add("BrokerProperties", "{}")
#Invoke-WebRequest call.
Invoke-WebRequest -Uri $uri -Headers $headers -Method Post -Body $body -UseBasicParsing
I've also tried generating it through a built in cmdlet in Az.ServiceBus
$ResourceGroupName = 'myResourceGroup'
$NameSpaceName = "serviceBusNameSpace"
$QueueName = "myQueueName"
$PolicyName = "RootManageSharedAccessKey"
$body = "test message"
$expiry = (Get-Date).AddHours(2)
$authRule = Get-AzServiceBusAuthorizationRule -ResourceGroupName $ResourceGroupName -Namespace $NamespaceName
$token = New-AzServiceBusAuthorizationRuleSASToken -AuthorizationRuleId $authRule.Id -KeyType Primary -ExpiryTime $Expiry
$headers = #{ "Authorization" = "SharedAccessSignature $($token.SharedAccessSignature)"; "Content-Type" = "application/atom+xml;type=entry;charset=utf-8" }
$uri = "https://$Namespace.servicebus.windows.net/$QueueName/messages"
$headers.Add("BrokerProperties", "{}")
#Invoke-WebRequest call.
Invoke-WebRequest -Uri $uri -Headers $headers -Method Post -Body $body -UseBasicParsing
Both give me a 401 unauthorized error
Invoke-WebRequest : The remote server returned an error: (401) Unauthorized.
At line:9 char:17
+ ... $response = Invoke-WebRequest -Uri $uri -Headers $headers -Method Pos ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
I'm not sure what else to do. Is there a setting I need to configure for my queue within the azure portal?
Have found solution. UTC time was originally expiring token before even sending, in addition to malformed SAS signature
Final code edit below
$key = (Get-AzServiceBusKey -ResourceGroupName $ResourceGroupName -Namespace $namespacename -Name $PolicyName).PrimaryKey
$origin = [DateTime]"1/1/1970 00:00"
$Expiry = (Get-Date).AddMinutes(20)
$Expiry = $Expiry.ToUniversalTime()
#compute the token expiration time.
$diff = New-TimeSpan -Start $origin -End $Expiry
$tokenExpirationTime = [Convert]::ToInt32($diff.TotalSeconds)
$uri = "https://$Namespace.servicebus.windows.net/$QueueName/messages"
$scope = "https://$Namespace.servicebus.windows.net/$QueueName"
#create the string that will be used when cumputing the hash
$stringToSign = [Web.HttpUtility]::UrlEncode($scope) + "`n" + $tokenExpirationTime
#Create a new instance of the HMACSHA256 class and set the key to UTF8 for the size of $Key
$hmacsha = New-Object -TypeName System.Security.Cryptography.HMACSHA256
$hmacsha.Key = [Text.Encoding]::UTF8.GetBytes($Key)
#Compute hash from the HMACSHA256 instance we created above using the size of the UTF8 string above.
$hash = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($stringToSign))
#Convert the hash to base 64 string
$signature = [Convert]::ToBase64String($hash)
#create the token
$token = [string]::Format([Globalization.CultureInfo]::InvariantCulture, `
"SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", `
[Web.HttpUtility]::UrlEncode($scope), `
[Web.HttpUtility]::UrlEncode($signature), `
$tokenExpirationTime, $PolicyName)
$headers = #{ "Authorization" = "$token"}
$headers.Add("Content-Type", "application/atom+xml;type=entry;charset=utf-8")
#Invoke-WebRequest call.
Invoke-WebRequest -Uri $uri -Headers $headers -Method Post -Body $body -UseBasicParsing
I have made some changes in your script and it is working fine.
$ResourceGroupName = 'myResourceGroup'
$Namespace = "serviceBusNameSpace"
$QueueName = "myQueueName"
$PolicyName = "RootManageSharedAccessKey"
$body = "test message"
$key = (Get-AzServiceBusKey -ResourceGroupName $ResourceGroupName -Namespace $Namespace -Name $PolicyName).PrimaryKey
$origin = [DateTime]"1/1/1970 00:00"
$Expiry = (Get-Date).AddMinutes(5)
#compute the token expiration time.
$diff = New-TimeSpan -Start $origin -End $Expiry
$tokenExpirationTime = [Convert]::ToInt32($diff.TotalSeconds)
#Create a new instance of the HMACSHA256 class and set the key to UTF8 for the size of $Key
$hmacsha = New-Object -TypeName System.Security.Cryptography.HMACSHA256
$hmacsha.Key = [Text.Encoding]::UTF8.GetBytes($Key)
#create the string that will be used when cumputing the hash
$stringToSign = [Web.HttpUtility]::UrlEncode($Namespace) + "`n" + $tokenExpirationTime
#Compute hash from the HMACSHA256 instance we created above using the size of the UTF8 string above.
$hash = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($stringToSign))
#Convert the hash to base 64 string
$signature = [Convert]::ToBase64String($hash)
#create the token
$token = [string]::Format([Globalization.CultureInfo]::InvariantCulture, `
"SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", `
[Web.HttpUtility]::UrlEncode($Namespace), `
[Web.HttpUtility]::UrlEncode($signature), `
$tokenExpirationTime, $PolicyName)
$headers = #{ "Authorization" = "$token"; "Content-Type" = "application/atom+xml;type=entry;charset=utf-8" }
$uri = "https://$Namespace.servicebus.windows.net/$QueueName/messages"
$headers.Add("BrokerProperties", "{}")
#Invoke-WebRequest call.
Invoke-WebRequest -Uri $uri -Headers $headers -Method Post -Body $body -UseBasicParsing
The changes which I have made are:
You don't need to create scope variable. You need to pass the $Namespace to stringToSign.
You don't need to use Get-AzServiceBusNamespace to get namespace name as you are already taking this as user input.
See post edit.
Token expiration time wasn't converted to UTC, making it always expired, in addition to not having the SaS token configuration string formed correctly.

Function Level Authorization Authorize keys in Azure can we manage these keys through CICD

Can we managae keys through CICD?
Means i need to manage these through CICD not portal or Rest Srevice is it possible?
everything is being managed through rest api (ultimately) so this ask makes very little sense. you can manage those only using the rest calls (as far as I know).
function Add-AzureFunctionKey {
Param(
[string]$appName,
[string]$resourceGroup,
[string]$funcKeyName,
[string]$funcKeyValue
)
$AzureContext = Get-AzureRmContext
if(!$AzureContext){
Write-Output "Please login to your Azure Account"
Login-AzureRmAccount
}
$SubscriptionId = (Get-AzureRmSubscription | select Name, State, SubscriptionId, TenantId | Out-GridView -Title "Azure Subscription Selector" -PassThru).SubscriptionId
Get-AzureRmSubscription -SubscriptionId $SubscriptionId | Select-AzureRmSubscription
$PublishingProfile = (Get-AzureRmWebAppPublishingProfile -ResourceGroupName $resourceGroup -Name $appName)
$user = (Select-Xml -Xml $PublishingProfile -XPath "//publishData/publishProfile[contains(#profileName,'Web Deploy')]/#userName").Node.Value
$pass = (Select-Xml -Xml $PublishingProfile -XPath "//publishData/publishProfile[contains(#profileName,'Web Deploy')]/#userPWD").Node.Value
$pair = "$($user):$($pass)"
$kuduCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$authToken = Invoke-RestMethod -Uri "https://$appName.scm.azurewebsites.net/api/functions/admin/token" -Headers #{Authorization = ("Basic {0}" -f $kuduCredentials)} -Method GET
$Functions = Invoke-RestMethod -Method GET -Headers #{Authorization = ("Bearer {0}" -f $authToken)} -Uri "https://$appName.azurewebsites.net/admin/functions"
$Functions = $Functions.Name
ForEach ($functionName in $Functions) {
$data = #{
"name" = "$funcKeyName"
"value" = "$funcKeyValue"
}
$json = $data | ConvertTo-Json;
$keys = Invoke-RestMethod -Method PUT -Headers #{Authorization = ("Bearer {0}" -f $authToken)} -ContentType "application/json" -Uri "https://$appName.azurewebsites.net/admin/functions/$functionName/keys/$funcKeyName" -body $json
Write-Output "Function $FunctionName Key updated $keys"
}
}
here's a sample found online, i didnt test it. there are a few examples online more or less like the one above.
Source: https://www.powershellbros.com/add-azure-function-key/

Resources