Any request from the above list will be allowed through and the Access-Control-Allow-Origin
set to the correct url? Other urls to be declined?
I have used below Powershell
code to allow requests from the approved URLs
to access the resource and will set the Access-Control-Allow-Origin
header to the correct URL
. Requests from other origins will be declined.
$appGW = Get-AzApplicationGateway -Name "<ApplicationGateway-Name>" -ResourceGroupName "<ResourceGroupName>"
$corsAllowedURLs = @"
{
"AllowedURLs": [
"https://site1.example.com",
"https://site2.example.com",
"https://funkyChicken.farm.com"
]
}
"@
$corsAllowedURLsObj = ConvertFrom-Json $corsAllowedURLs
# Construct the regex pattern for the allowed URLs
$x = $corsAllowedURLsObj.AllowedURLs
$Reg = @()
foreach ($App in $x) {
if ($Reg -eq $null) {
$Reg = $App
} else {
$Reg += "|" + $App
}
}
$Reg = $Reg -replace "^\|", ""
$u = $Reg
$us = $u -split ' '
$pattern = $us[0] + '|' + $us[1] + '|' + ($us[2..($us.Count - 1)] -join ' ')
$corsPattern = $pattern -join ' '
$corsActionSet = New-AzApplicationGatewayRewriteRuleActionSet
$corsHeaderConfiguration = New-AzApplicationGatewayRewriteRuleHeaderConfiguration -HeaderName "Access-Control-Allow-Origin" -HeaderValue $corsPattern
$corsActionSet.ResponseHeaderConfigurations = $corsHeaderConfiguration
$corsCondition = New-AzApplicationGatewayRewriteRuleCondition -Variable "var_request_uri" -Pattern ".*" -IgnoreCase
$corsRule = New-AzApplicationGatewayRewriteRule -Name "CORS1" -ActionSet $corsActionSet -Condition $corsCondition
$result = Add-AzApplicationGatewayRewriteRuleSet -Name "CORSPro" -RewriteRule $corsRule -ApplicationGateway $appGW
$appGW | Set-AzApplicationGateway
Output:

Once I ran the above code Urls
are added to Application Gateway
rewrites rules.
Portal Output:

Refer the Stack Link for more details.