Dealing With Cross Site Origin Restrictions

unsplash_img

I started out with testing an issue which I was facing on my setup. My setup included an API server written in Golang and a HTML client code which is to be run on browser. This backend server hosted HTTP and Websocket API endpoints:

To achieve above cookie based authentication, I planned to test it out locally with minimal code before applying my changes on production code. So two main things to be achieved once Cookie is sent as part of Login response:

  1. Ensure that the cookie is set for all the authenticated HTTP API requests by the Browser
  2. Ensure that the cookie is set for all the authenticated Websocket API requests by the Browser

Local Testing with cross origin requests

I performed my testing on Chrome browser (Version 90) and below steps are only tested on the mentioned browser. But before we look at the cross-origin requests, we must understand CORS restriction. Here's a nice article to understand this.

Hence we deal with two different origins:

  1. http://localhost:8800 : Python Webserver
  2. http://localhost:1323: Golang Backend Server

When we open URL #1, it makes requests to URL #2. This is cross origin requests and it is blocked by browsers for security reasons

Sample code:

Now because we are dealing with different origins, requests to backend server from browser via webserver will not go through. Here's browser console log on perfoming the following actions:

  1. Open http://localhost:1323/test_client.html
  2. Click Login text

To allow access to such cross origins, we use the following CORS policy in our API server code:

Now when we open http://localhost:8800/test_client.html and click Login text, it will go through

But then when we click ShowData text, we see following error in Browser's console:

This is because we didn't set XMLHttpRequest.withCredentials it to true. This is required for browser to store cookie or any other credentials like authorization headers or TLS client certificates for cross-site requests

Hence we'll need the following changes:

  1. In HTML client code, set withCredentials to true:

  2. In API server code, update CORS policy:

This should now fix the cookie issue.

Summary