DEV Community

Zubair Mohsin
Zubair Mohsin

Posted on

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 👨🏽‍💻

Top comments (4)

Collapse
 
diek profile image
diek

Well, the security concern you say is not accurate. Every one, from everywhere, can ask to your service, if you haven't network configuration to prevent it. CORS is an automatic block only for browsers. I think a ddos from a browser is not a concern, but it is the cookie one. Stealing cookies is not hard to make if the server has miss configuration, aka Apache/nginx.
Anyway! It's a good post, talking about the usually unknown Mr. CORS is good. Thank you for share knowledge 😊

Collapse
 
zubairmohsin33 profile image
Zubair Mohsin

Hi. Thank you for your comment.

Can you share more about "Stealing cookies is not hard to make if the server has miss configuration, aka Apache/Nginx" ?

Currently I am setting cookies in a response from PHP using setcookie method. It would be helpful if you can share more about Apache/Nginx involvement here.

Thanks :)

Collapse
 
diek profile image
diek

Hi Zubair, there are tools that automatically steal cookies session. Search about that, usually those tools are included in kali linux or it can be manually installed in linux/unix.

Collapse
 
edsulaiman20 profile image
Edwin Sulaiman

thanks, nice post you are my hero for handling cors