Sending cookies with Cross Origin (CORS) request

Zubair Mohsin - Feb 9 '20 - - Dev Community

Implementation:

We need to do two things:

  • Include withCredentials : true in your Ajax request.

For plain XMLHttpRequest like below:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://cross_origin_url', true);
xhr.withCredentials = true;
xhr.send(null);
Enter fullscreen mode Exit fullscreen mode

For jQuery:


$.ajax({
  url: //cross origin url
  xhrFields: {
        withCredentials: true
   }

})
Enter fullscreen mode Exit fullscreen mode
  • Secondly, from your server side we need to send a Response header which is: Access-Control-Allow-Credentials and set its value to true.

Access-Control-Allow-Credentials: true

PHP example:

header('Access-Control-Allow-Credentials: true');
Enter fullscreen mode Exit fullscreen mode

In Laravel we can do:

public function index()
{
   return response()->header('Access-Control-Allow-Credentials', true);
}
Enter fullscreen mode Exit fullscreen mode

Security Concerns:

  • DDoS. If you have set Access-Control-Allow-Origin: *, any person with any domain will be able to send request to your URL.

  • If someone can copy the Cookie value from browser ( even if its encrypted ) and send it along with request, it will be a legit request.

  • Consider throttling ( rate limiting ) for such urls in your application.
  • Perform verification in a middleware for such request to verify its coming from a trusted source.

That's it 🙌🏼 Happy Coding 👨🏽‍💻

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player