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);
For jQuery:
$.ajax({
url: //cross origin url
xhrFields: {
withCredentials: true
}
})
- 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');
In Laravel we can do:
public function index()
{
return response()->header('Access-Control-Allow-Credentials', true);
}
Security Concerns:
DDoS
. If you have setAccess-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 👨🏽💻