When you enable a REST service to accept the CORS header, by default, the service accepts any CORS request. Your REST service should examine the CORS requests and decide whether to proceed. For example, you can provide an allow list containing domains that contain only trusted scripts. To do this, you need to:
The net result is that the dispatch class inherits from your custom class instead of from %CSP.RESTOpens in a new tab and thus uses your definition of OnHandleCorsRequest(), which overrides the default CORS header processing.
Defining OnHandleCorsRequest()
In your subclass of %CSP.RESTOpens in a new tab, define the OnHandleCorsRequest() method, which needs to examine the CORS requests and set the response header appropriately.
To define this method, you must be familiar with the details of the CORS protocol (not discussed here).
You also need to know how to examine the requests and set the response headers. For this, it is useful to examine the method that is used by default, the HandleDefaultCorsRequest() method of %CSP.RESTOpens in a new tab. This section explains how this method handles the origin, credentials, header, and request method and suggests variations. You can use this information to write your OnHandleCorsRequest() method.
The following code gets the origin and uses it to set the response header. One possible variation is to test the origin against an allow list. Then the domain is allowed, set the response header. If not, set the response header to an empty string.
#; Get the origin
Set tOrigin=$Get(%request.CgiEnvs("HTTP_ORIGIN"))
#; Allow requested origin
Do ..SetResponseHeaderIfEmpty("Access-Control-Allow-Origin",tOrigin)
The following lines specify that the authorization header should be included.
#; Set allow credentials to be true
Do ..SetResponseHeaderIfEmpty("Access-Control-Allow-Credentials","true")
The following lines get the headers and the request method from the incoming request. Your code should test if the headers and request method are allowed. If they are allowed, use them to set the response headers. If not, set the response header to an empty string.
#; Allow requested headers
Set tHeaders=$Get(%request.CgiEnvs("HTTP_ACCESS_CONTROL_REQUEST_HEADERS"))
Do ..SetResponseHeaderIfEmpty("Access-Control-Allow-Headers",tHeaders)
#; Allow requested method
Set tMethod=$Get(%request.CgiEnvs("HTTP_ACCESS_CONTROL_REQUEST_METHOD"))
Do ..SetResponseHeaderIfEmpty("Access-Control-Allow-Method",tMethod)
Important:
The default CORS header processing is not suitable for REST services handling confidential data.