قالب وردپرس درنا توس
Home / Tips and Tricks / Handling CORS in Web Applications – CloudSavvy IT

Handling CORS in Web Applications – CloudSavvy IT



data center
Shutterstock / Gorodenkoff

CORS is a browser mechanism that allows servers to specify the origin of third parties that can request resources from them. It is a security protection that helps prevent malicious sites from stealing data owned by other sources.

CORS stands for Cross Origin Resource Sharing. When using CORS to load a resource, the browser usually sends a “preflight”

; HTTP OPTIONS request. The server should respond stating the origin it will communicate with. It can also define additional restrictions such as the HTTP headers that can be sent.

The browser checks the current origin and outgoing request against the server’s specifications. The request may proceed if all checks are successful. Otherwise, the original request will be cancelled. You will see a warning in the console when this happens.

When CORS is used

Browsers enforce CORS for Ajax and Fetch requests. The mechanism will also be used for web fonts, WebGL textures and canvas images with drawImage(). Any eligible request to a third party requires a CORS exchange.

CORS is not enforced if the request is considered “simple”. A simple request should be: GET, HEAD or POST with a content type of text/plain, application/x-www-form-urlencoded or multipart/form-data. The only allowed headers for simple requests are: Accept, Accept-Language, Content-Language and Content-Type.

If the request does not meet all of the above criteria, a CORS exchange is initiated by modern browsers. It is important to recognize that CORS is a browser-based technology – you will never encounter CORS when making requests manually, as with curl in your terminal.

CORS exchanges don’t always send a OPTIONS preflight request. A preflight is used when the request would cause “updates” on the server. This is generally the case for application methods other than: GET.

Imagine POST request to /api/users/create. The server would always create a new user, but the browser may deny access to the response if the request was subject to CORS. By sending a OPTIONS request first, the server has a chance to explicitly de for real request. This ensures that the user account is not actually created.

Handling CORS Client Side

Although CORS is a browser technology, you cannot directly affect it with client-side code. This prevents malicious scripts from bypassing CORS protections to load data from third-party domains.

CORS is usually transparent so you don’t know it’s in operation. If a CORS exchange fails, your JavaScript code will see a general network error. It is not possible to get precise details about what went wrong as this would be a security risk. Full details are recorded in the console.

The only way to fix a CORS error is to make sure your server is sending the correct response headers. Now let’s see how that is done.

Handling CORS Server-Side

You must first make sure that your server is processing OPTIONS apply correctly. You may need to create a new route in your web framework. In general you have to accept OPTIONS requests to any endpoint that may receive a cross-origin request from a browser. The answer does not have to have a body, but must contain specific headers that inform the browser how to proceed.

Start adding the Access-Control-Allow-Origin head. This specifies the origin of the third party that is allowed to communicate with your endpoint. Only one origin can be specified; you can handle multiple origins by dynamically setting the value of the header to the origin from which the request was sent. You can get the current origin of the Origin request headline.

Access-Control-Allow-Origin accepts * as a special wildcard value. This allows CORS requests from all origin. Be careful when using this – being specific with the allowed origin gives you more control and prevents malicious scripts from requesting data from your server.

Access-Control-Allow-Origin should be included in your server’s response to the real request, as well as the OPTIONS reaction. Once this single header is set, basic exchange with an external browser client is allowed.

CORS requests usually only support the “simple” request headers listed above. If you need to use a different header like: Authorization or a custom header, your server must explicitly allow it in the preflight response.

Set the Access-Control-Allow-Headers head. The value must be a comma-separated list of header names that will be accepted with the real request.

Access-Control-Allow-Headers: Authorization, X-Custom-Header

The browser would now allow a request with either the Authorization or X-Custom-Header headers to continue.

When the browser sends a CORS preflight request, it sends the Access-Control-Request-Headers head. This contains the list of headers sent with the actual request. Your server code can use this information to determine how to respond to the preflight request.

Restrict to specific application methods

Similar to specifying request headers, server endpoints can define which HTTP methods should be allowed cross-origin. Set the Access-Control-Allow-Methods header as a comma separated list of method names.

Access-Control-Allow-Methods: GET, POST, DELETE

The browser sends the Access-Control-Request-Method header with CORS preflights. This will let your server know which HTTP method will be used to make the final request.

Cookies and references

CORS requests do not normally send cookies because they may contain sensitive credentials that identify the sender. If you need to include cookies with a cross-origin request, you must explicitly enable it in your client-side code:

fetch("https://localhost/demo", {
    mode: "cors",
    credentials: "include"
});

In addition, the server must Access-Control-Allow-Credentials: true response header to indicate that he agrees that cookies with credentials can be exchanged.

When using Access-Control-Allow-Credentials, you can not use the wildcard (*) with Access-Control-Allow-Origin. The server must instead specify an explicit origin to ensure user privacy. If the wildcard is sent, the browser will fail the request with a CORS error.

Preflight Caching

CORS OPTIONS preflights add an overhead to every request you make. While the delay should be barely noticeable on a good network connection, calling the same endpoint multiple times in quick succession is still a waste.

You can tell the browser to cache preflight responses by setting the Access-Control-Max-Age head. The value must be the time in seconds that the browser is allowed to cache the response. Subsequent requests to the same endpoint within the specified time period will not send a CORS preflight.

Conclusion

CORS can seem confusing the first time you encounter it. It is a browser technology that is controlled by server responses. CORS is unavoidable yet uncontrollable unless you have access to the server-side code you are communicating with.

The actual implementation of CORS is quite simple. Make sure your API or CDN is sending the correct response headers, especially Access-Control-Allow-Origin. You then have secure communication between different origins that helps protect you from bad actors.


Source link