0

I have a requirement to set the Access-Control-Allow-Origin.

I am requested not to use * for the value, but the api must allow multiple origins.

Is it possible to use regEx/AppGateway rewrites and have an allowed list or URL's that will rewrite the Access-Control-Allow-Origin?

E.g.

Approved URL's = [
  https://site1.example.com,
  https://site2.example.com,
  https://funkyChicken.farm.com
]

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?

user3067684
  • 936
  • 9
  • 18

1 Answers1

0

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:

enter image description here

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

Portal Output:

enter image description here

Refer the Stack Link for more details.

Venkat V
  • 2,197
  • 1
  • 1
  • 10