CORS settings with environment variables

Official Content
This documentation is valid for:

What is CORS?

Cross Origin Resource Sharing - CORS is a standard that allows servers to relax the same-origin policy. This is used to allow some cross-origin requests explicitly while rejecting others. For example, if a site offers an embeddable service, it may be necessary to relax certain restrictions.

When CORS is not enabled, and the Application and Service URL are in different domains, the WebBrowser will print the following error in the Console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://some-url-here. (Reason: additional information here).

Fortunately, GeneXus supports handling CORS-required headers in order to ensure the correct behavior of the Application.

Typically this is necessary for Angular applications, which call REST Services that are eventually deployed in another domain.

How to enable CORS headers in a GeneXus Application?

The environment variable GX_CORS_ALLOW_ORIGIN enables CORS for the selected host.

The values accepted by the variable are URL or "*". For example, https://foo.example.

Note: In the .NET Generator, it is possible to assign a comma-separated list of domains to the variable. For example, CORS_ALLOW_ORIGIN=https://foo.example,https://another.domain.

When GX_CORS_ALLOW_ORIGIN environment variable is enabled, the generated Application will return the following headers, according to the CORS specification:

Example Response of an OPTIONS Request to a GeneXus REST Endpoint: 

Access-Control-Allow-Origin: https://myapp.domain.com
Access-Control-Allow-Headers: GET, POST
Access-Control-Max-Age: 86400
Access-Control-Allow-Credentials: true

CORS in .NET Framework Generator

When the GX_CORS_ALLOW_ORIGIN environment variable is defined, the preflight OPTIONS request may not return the expected headers (as defined above).

It may be due to the configuration of handler mappings in IIS. To fix it, configure the OPTIONSVerbHandler to execute after wcf handlers (svc-Integrated-4.0).

  1. In IIS console, select "Handler Mappings" (either on server level or site level; beware that on the site level it will redefine all the handlers for your site and ignore any change done at the server level after that. Of course, on the server level, this could break other sites if they need their own handling of options verb).

  2. In Action pane, select "View ordered list..." Seek OPTIONSVerbHandler, and move it down until it is below svc-Integrated-4.0 handler.

Note: If OPTIONSVerbHandler is removed, it will break the response to preflight OPTIONS request for API objects.

Scope

Generators: Java, .NET, .NET Framework

Availability

This feature is available since GeneXus 18.

See Also 

Environment variables definition
Methods for reading environmental variables