Container Apps - Struggling with CORS
- Part 1 - Container Apps Environment
- Part 2 - The sessions service
- Part 3 - Scaling with KEDA
- Part 4 - Struggling with CORS
OK, here is the problem… You want to host an Azure Function App in a Docker container using Azure Container Apps. Now if you followed along with the previous posts you found that the Container Apps solution is just spot on and awesome, but lacks some features, and the ability to control CORS settings is one of them.
Now my Function App has an HTTP Triggered function that will be called from a front-end system, so the ability to control CORS settings is a must because else the front-end requests will never reach the server. If you run your container local host, you can set allowed hostnames in the local.settings.json
file. Now when you deploy this App to an Azure Function App in the Azure Cloud, you have the ability to control CORS settings on the Function App service. But on Container Apps… less results…
Help is on the way
So I posted a message on the socials and the one and only Anthony Chu (@anthonychu@hachyderm.io & https://twitter.com/nthonychu) picked it up and helped me out. It appears that the function host has the ability to set allowed origins and event support credentials (or not).
Setting allowed CORS origins
The trick is to set an environment variable called CORS_ALLOWED_ORIGINS
with a JSON array value containing all the hostnames you want to allow CORS requests from. For example ["https://your.host.com", "https://your.orther.host:4200"]
. Alternatively, you can allow all origins by setting ["*"]
as its value.
Supporting credentials
In case you want to support credentials, you need to set an environment variable called CORS_SUPPORT_CREDENTIALS
to true
. Its default value is false
, so if you don’t want to support credentials, you can leave the setting out.
Container name
Now somewhere deep inside the function host code, is a tricky if
statement that (when true) will pick up these environment variables above and use them to set a CORS policy. Now for container apps, this if only returns true if there is a ContainerName variable that has any value. Unfortunately, this environment variable is not set automagically, so you have to manually set it. The name of the environment variable is CONTAINER_NAME
and its value can be of any valid string. I used “banana” and it works.
Last modified on 2022-11-24