Logo

dev-resources.site

for different kinds of informations.

Sending cookies with Cross Origin (CORS) request

Published at
2/9/2020
Categories
javascript
php
xhr
cors
Author
zubairmohsin33
Categories
4 categories in total
javascript
open
php
open
xhr
open
cors
open
Author
14 person written this
zubairmohsin33
open
Sending cookies with Cross Origin (CORS) request

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 ๐Ÿ‘จ๐Ÿฝโ€๐Ÿ’ป

Featured ones: