programming software tips

testing CORS headers with PowerShell

CORS can be a pain in the ass to test for your backend service. This because you have to emulate a cross domain request from a browser and sometimes you just want to quickly confirm your CORS configuration or code is working. Can this be done using PowerShell, so you don’t have to fire up a test site to do that request, or use special tooling like Postman or whatever?

Well yes! Using the statement below you can see all the headers that are returned from the request to the test URL on your API. If CORS is correctly configured, you will see the Access-Control-Allow-Origin header in that list. It contains the allowed origin site domain or the asterisk to indicate any domain is allowed.
If not, something is still wrong.

(Invoke-WebRequest -UseBasicParsing -Headers @{ "Origin" = "" }).Headers

The trick is passing in the Origin header when you make the request. Without it, you won’t get any CORS headers back in most cases. I tested this using an ASP.NET Core backend by the way, but most backend systems should behave in the same way, as this is how browsers do it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.