{"id":269287,"date":"2021-06-08T17:00:16","date_gmt":"2021-06-08T14:00:16","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/handling-cors-in-web-applications-cloudsavvy-it\/"},"modified":"2021-06-08T17:00:16","modified_gmt":"2021-06-08T14:00:16","slug":"handling-cors-in-web-applications-cloudsavvy-it","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/handling-cors-in-web-applications-cloudsavvy-it\/","title":{"rendered":"#Handling CORS in Web Applications \u2013 CloudSavvy IT"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a3be3c0502e6\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #dd3333;color:#dd3333\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #dd3333;color:#dd3333\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a3be3c0502e6\" checked aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/buradabiliyorum.com\/en\/handling-cors-in-web-applications-cloudsavvy-it\/#When_CORS_Is_Used\" >When CORS Is Used<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/buradabiliyorum.com\/en\/handling-cors-in-web-applications-cloudsavvy-it\/#Handling_CORS_Client-Side\" >Handling CORS Client-Side<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/buradabiliyorum.com\/en\/handling-cors-in-web-applications-cloudsavvy-it\/#Handling_CORS_Server-Side\" >Handling CORS Server-Side<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/buradabiliyorum.com\/en\/handling-cors-in-web-applications-cloudsavvy-it\/#Limiting_to_Specific_Request_Methods\" >Limiting to Specific Request Methods<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/buradabiliyorum.com\/en\/handling-cors-in-web-applications-cloudsavvy-it\/#Cookies_and_Credentials\" >Cookies and Credentials<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/buradabiliyorum.com\/en\/handling-cors-in-web-applications-cloudsavvy-it\/#Preflight_Caching\" >Preflight Caching<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/buradabiliyorum.com\/en\/handling-cors-in-web-applications-cloudsavvy-it\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<p><strong>&#8220;#Handling CORS in Web <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/download-scripts-themes-apps\/\" data-internallinksmanager029f6b8e52c=\"9\" title=\"Download Scripts &amp; Themes &amp; Apps\" target=\"_blank\" rel=\"noopener\">App<\/a>lications \u2013 CloudSavvy IT&#8221;<\/strong><\/p>\n<div id=\"article-content-area\">\n<figure style=\"width: 2364px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"type:primaryImage wp-image-11849 size-full\" data-pagespeed-lazy-src=\"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/05\/0fa81627.png?width=1198&amp;trim=1,1&amp;bg-color=000&amp;pad=1,1\" alt=\"data center\" width=\"2364\" height=\"1260\" src=\"https:\/\/www.shutterstock.com\/image-photo\/shot-corridor-working-data-center-full-1062915266\" data-credittext=\"Shutterstock\/Gorodenkoff\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><figcaption class=\"wp-caption-text\"><span class=\"type:primaryImage imagecredit\"><a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/www.shutterstock.com\/image-photo\/shot-corridor-working-data-center-full-1062915266\">Shutterstock\/Gorodenkoff<\/a><\/span><\/figcaption><\/figure>\n<p>CORS is a browser mechanism which lets servers specify the third-party origins that can request resources from them. It\u2019s a security protection which helps stop malicious sites from stealing data owned by other origins.<\/p>\n<p><a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTTP\/CORS\">CORS stands for<\/a> Cross-Origin Resource Sharing. When CORS is used to load a resource, the browser usually sends a \u201cpreflight\u201d HTTP <code>OPTIONS<\/code> request. The server must respond specifying the origins it will interact with. It may also define additional constraints, such as the HTTP headers which can be sent.<\/p>\n<p>The browser checks the current origin and the outgoing request against the server\u2019s specifications. The request is allowed to continue if all the checks pass. Otherwise, the original request will be cancelled. You see a warning in the console when this happens.<\/p>\n<h2 id=\"when-cors-is-used\"><span class=\"ez-toc-section\" id=\"When_CORS_Is_Used\"><\/span>When CORS Is Used<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Browsers enforce CORS for Ajax and Fetch requests. The mechanism will <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTTP\/CORS\">also be used<\/a> for web fonts, WebGL textures and canvas image draws with <code>drawImage()<\/code>. Any eligible request to a third-party origin will require a CORS exchange to take place.<\/p>\n<p>CORS won\u2019t be enforced if the request is seen as \u201csimple\u201d. A simple request must be <code>GET<\/code>, <code>HEAD<\/code> or <code>POST<\/code> with a content type of <code>text\/plain<\/code>, <code>application\/x-www-form-urlencoded<\/code> or <code>multipart\/form-data<\/code>. The only permissible simple <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTTP\/CORS\">request headers are<\/a> <code>Accept<\/code>, <code>Accept-Language<\/code>, <code>Content-Language<\/code> and <code>Content-Type<\/code>.<\/p>\n<p>If the request doesn\u2019t meet all of the above criteria, a CORS exchange will be commenced by modern browsers. It\u2019s important to recognise CORS is a browser-based <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/technology\/\" data-internallinksmanager029f6b8e52c=\"4\" title=\"Technology\" target=\"_blank\" rel=\"noopener\">technology<\/a> \u2013 you won\u2019t ever encounter CORS while making requests manually, such as with <code>curl<\/code> in your terminal.<\/p>\n<p>CORS exchanges don\u2019t always send an <code>OPTIONS<\/code> preflight request. A preflight is used when the request would cause \u201cside effects\u201d on the server. This is <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/general\/\" data-internallinksmanager029f6b8e52c=\"3\" title=\"General\" target=\"_blank\" rel=\"noopener\">general<\/a>ly the case for request methods other than <code>GET<\/code>.<\/p>\n<p>Imagine a <code>POST<\/code> request to <code>\/api\/users\/create<\/code>. The server would always create a new user but the browser may refuse access to the response if the request was subject to CORS. By sending an <code>OPTIONS<\/code> request first, the server has a chance to explicitly decline the <em>real<\/em> request. This ensures the user account isn\u2019t actually created.<\/p>\n<h2 id=\"handling-cors-client-side\"><span class=\"ez-toc-section\" id=\"Handling_CORS_Client-Side\"><\/span>Handling CORS Client-Side<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Although CORS is a browser technology, you can\u2019t directly influence it with client-side code. This prevents malicious scripts from side-stepping CORS protections to load data from third-party domains.<\/p>\n<p>CORS is usually transparent so you won\u2019t be aware it\u2019s in operation. If a CORS exchange does fail, your JavaScript code will see a generic network error. It\u2019s not possible to get precise details of what went wrong, as this would be a security risk. The full details are logged to the console.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-10004\" data-pagespeed-lazy-src=\"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/03\/e1994dc7.jpg?trim=1,1&amp;bg-color=000&amp;pad=1,1\" alt=\"\" width=\"960\" height=\"540\" src=\"\/pagespeed_static\/1.JiBnMqyl6S.gif\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>The only way of resolving a CORS failure is to make sure your server sends the correct response headers. Lets now look at how that is done.<\/p>\n<h2 id=\"handling-cors-server-side\"><span class=\"ez-toc-section\" id=\"Handling_CORS_Server-Side\"><\/span>Handling CORS Server-Side<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>You should firstly make sure your server handles <code>OPTIONS<\/code> requests correctly. You might need to create a new route in your web framework. You\u2019ll generally need to accept <code>OPTIONS<\/code> requests to each endpoint that might receive a cross-origin request from a browser. The response doesn\u2019t need to have a body but must include specific headers that inform the browser how to proceed.<\/p>\n<p>Begin by adding the <code>Access-Control-Allow-Origin<\/code> header. This specifies the third-party origin which is allowed to communicate with your endpoint. Only one origin can be specified; you can handle multiple origins by dynamically setting the header\u2019s value to the origin the request was sent from. You can get the current origin from the <code>Origin<\/code> request header.<\/p>\n<p><code>Access-Control-Allow-Origin<\/code> accepts <code>*<\/code> as a special wildcard value. This will allows CORS requests from <em>all<\/em> origins. Take care when using this \u2013 being specific with the allowed origins gives you more control and prevents malicious scripts from requesting data from your server.<\/p>\n<p><code>Access-Control-Allow-Origin<\/code> must be included in your server\u2019s response to the real request, as well as the <code>OPTIONS<\/code> response. Once this single header is setup, a basic exchange with a third-party browser client will be permitted.<\/p>\n<p>CORS requests usually only support the \u201csimple\u201d request headers listed above. If you need to use any other header, such as <code>Authorization<\/code> or a custom header, your server will need to explicitly allow it in the preflight response.<\/p>\n<p>Set the <code>Access-Control-Allow-Headers<\/code> header. Its value should be a comma-separated list of header names which will be accepted with the real request.<\/p>\n<pre>Access-Control-Allow-Headers: Authorization, X-Custom-Header<\/pre>\n<p>The browser would now permit a request with either the <code>Authorization<\/code> or <code>X-Custom-Header<\/code> headers to continue.<\/p>\n<p>When the browser sends a CORS preflight request, it will send the <code>Access-Control-Request-Headers<\/code> header. This contains the list of headers that will be sent with the actual request. Your server code can use this information when determining how to respond to the preflight request.<\/p>\n<h2 id=\"limiting-to-specific-request-methods\"><span class=\"ez-toc-section\" id=\"Limiting_to_Specific_Request_Methods\"><\/span>Limiting to Specific Request Methods<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Similarly to specifying request headers, server endpoints can define which HTTP methods should be allowed cross-origin. Set the <code>Access-Control-Allow-Methods<\/code> header as a comma-separated list of method names.<\/p>\n<pre>Access-Control-Allow-Methods: GET, POST, DELETE<\/pre>\n<p>The browser sends the <code>Access-Control-Request-Method<\/code> header with CORS preflights. This lets your server know the HTTP method which will be used to make the final request.<\/p>\n<h2 id=\"cookies-and-credentials\"><span class=\"ez-toc-section\" id=\"Cookies_and_Credentials\"><\/span>Cookies and Credentials<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>CORS requests don\u2019t normally send cookies as they could contain sensitive credentials identifying the sender. If you need to include cookies with a cross-origin request, you must explicitly enable this in your client-side code:<\/p>\n<pre escaped=\"true\" lang=\"javascript&quot;\">fetch(\"https:\/\/localhost\/demo\", {&#13;\n    mode: \"cors\",&#13;\n    credentials: \"include\"&#13;\n});<\/pre>\n<p>In addition, the server must set the <code>Access-Control-Allow-Credentials: true<\/code> response header to signal its agreement that credentialled cookies can be exchanged.<\/p>\n<p>When using <code>Access-Control-Allow-Credentials,<\/code> you <strong>cannot<\/strong> use the wildcard (<code>*<\/code>) with <code>Access-Control-Allow-Origin<\/code>. The server must specify an explicit origin instead to safeguard user privacy. If the wildcard is sent, the browser will fail the request with a CORS error.<\/p>\n<h2 id=\"preflight-caching\"><span class=\"ez-toc-section\" id=\"Preflight_Caching\"><\/span>Preflight Caching<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>CORS <code>OPTIONS<\/code> preflights do add an overhead to each request you make. Although the delay should be barely perceptible on a good network connection, it\u2019s nonetheless wasteful when you\u2019re calling the same endpoint multiple times in quick succession.<\/p>\n<p>You can tell the browser to cache preflight responses by setting the <code>Access-Control-Max-Age<\/code> header. The value should be the time in seconds that the browser is allowed to cache the response for. Subsequent requests to the same endpoint within the given period will not send a CORS preflight.<\/p>\n<h2 id=\"conclusion\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>CORS can seem confusing the first time you encounter it. It\u2019s a browser technology which is controlled by server responses. CORS is unavoidable and yet also uncontrollable, unless you have access to the server-side code you\u2019re interacting with.<\/p>\n<p>The actual implementation of CORS is quite straightforward. Make sure your API or CDN is sending the right response headers, most notably <code>Access-Control-Allow-Origin<\/code>. You\u2019ll then have safe cross-origin communication that helps guard against bad actors.\n<\/div>\n<blockquote><p><strong><span style=\"color: #ff6600;\">If you liked the article, do not forget to share it with your friends. Follow us on\u00a0<span style=\"color: #ff0000;\"><a style=\"color: #ff0000;\" href=\"https:\/\/news.google.com\/publications\/CAAqBwgKMLG0nwswvr63Aw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">Google News<\/a><\/span>\u00a0too, click on the star and choose us from your favorites.<\/span><\/strong><\/p><\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\">For forums sites go to <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/forum.buradabiliyorum.com\/\" target=\"_blank\" rel=\"noopener\">Forum.BuradaBiliyorum.Com<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\"><strong>If you want to read more like this article, you can visit our <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/en.buradabiliyorum.com\/technology\/\" target=\"_blank\" rel=\"noopener\">Technology category.<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<p><span style=\"color: black;\"><a style=\"color: #ff9900;\" href=\"https:\/\/www.cloudsavvyit.com\/10001\/handling-cors-in-web-applications\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;#Handling CORS in Web Applications \u2013 CloudSavvy IT&#8221; Shutterstock\/Gorodenkoff CORS is a browser mechanism which lets servers specify the third-party origins that can request resources from them. It\u2019s a security protection which helps stop malicious sites from stealing data owned by other origins. CORS stands for Cross-Origin Resource Sharing. When CORS is used to load&#8230;<\/p>\n","protected":false},"author":1,"featured_media":269288,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"fifu_image_url":"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/05\/0fa81627.png","fifu_image_alt":"","footnotes":""},"categories":[18],"tags":[],"class_list":["post-269287","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/269287","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/comments?post=269287"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/269287\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/269288"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=269287"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=269287"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=269287"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}