Testing CORS with POSTman

I’ve just added CORS support to my Web API and have spend a not inconsiderable amount of time chasing my tail and trying all sorts of different things to try and get it working. Let me explain …

I use the POSTman chrome extension to test my API (outside of unit/integration tests) and whenever I made a request I wasn’t getting back the expected Access-Control-Allow-Origin header in the response. So, I loaded up fiddler after scratching my head for a while and I could see the Origin header wasn’t being sent in the request. Apparently chrome restricts that header, so it was getting stripped out. I could have used the POSTman python proxy (https://github.com/a85/POSTMan-Chrome-Extension/wiki/Postman-Proxy) but since I already have fiddler I simply customised it a little. I started off by adding a new RulesOption and hard-coding the Origin in fiddler, like so …

    class Handlers
    {
        ...
        public static RulesOption("Add Origin Header")
        var m_AddOriginHeader: boolean = false;
        ...
        static function OnBeforeRequest(oSession: Session) {
        ...
            if (m_AddOriginHeader)
            {
                oSession.oRequest["Origin"] = "http://localhost/";
            }
        ...
        }
    ...
    }

But, that didn’t allow me to control the origin. It’s not applicable in this instance, but I figured I might want to add specific origins in other instances, so I came up with this …

    class Handlers
    {
        ...
        static function OnBeforeRequest(oSession: Session) {
        ...
            if (oSession.oRequest.headers.Exists("X-Origin"))
            {
                oSession.oRequest["Origin"] = oSession.oRequest["X-Origin"];
                oSession.oRequest.headers.Remove("X-Origin");
            }
        ...
        }
    ...
    }

So, all I need to do now is add the X-Origin header in place of the Origin header and I’m good to go. Obviously, I will need fiddler to be running and capturing traffic in order it to work. But, if fiddler is not running then the request still works but without the CORS header being returned in the response.

Advertisements

One response to “Testing CORS with POSTman

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s