CORS

Last change on 2023-04-04 • Created on 2023-03-28 • ID: KO-1C835

Cross-origin resource sharing (CORS) is a mechanism that allows web applications to access resources from different sources on the internet, even if those sources are from different domains. CORS is an important technology for securing web applications and can help prevent attacks such as cross-site scripting (XSS) and cross-site request forgery (CSRF).

CORS allows you to control which sources APIs run from and makes it possible to access interfaces running under a different domain. Here are some important settings you need to pay attention to:

  • Access-Control-Allow-Methods => which methods (GET, POST etc.) should be allowed

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods

  • Access-Control-Allow-Origin => from which domains is the access permitted

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

  • Access-Control-Allow-Headers => which headers may be transmitted during the request (optional)

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers

In addition, CORS preflight requests must be allowed. Here the browser carries out corresponding OPTIONS requests in order to check in advance whether the API is configured correctly and access is permitted. An HTTP 200 should also be returned here as a status code.

Here is an example. Let's assume that there is access to https://testen.de, which integrates an external API ( https://api.example.com ). In the example, a content-type header is also transmitted.

In this situation, you would need to create or edit an .htaccess file in the start directory of api.example.com. You could structure this like what you see below. (Please pay attention to the comments):

# Here you have to provide the "supported" HTTP methods. OPTIONS shall *always* be included, you can find further inforamtion regarding this setting at:
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
# This should be configured according to your requirements:
header always set Access-Control-Allow-Methods OPTIONS,GET,POST,PUT

# Here you have to specify, from which domains the access is permitted. It's supported to specify multiple domains comma separated:
header always set Access-Control-Allow-Origin https://testen.de

# OPTIONAL allowing further custom HTTP headers:
header always set Access-Control-Allow-Headers Content-Type

# The HTTP Status Code shall only be enforced for preflight (OPTIONS) requests. When confgiuring this for all domains, it would harm the functionality of the website.
<If "%{REQUEST_METHOD} == 'OPTIONS'">
        # Change the HTTP Status Code to 200 (successfully)
        RewriteRule ^ - [R=200,L]
</If>

The interface at https://api.example.com can then be accessed easily within the application (https://testen.de) using CORS.