CORS for Zoho CRM APIs
Consider that you want to fetch the list of Prospects or Deals from Zoho CRM and display it in your web app hosted in a different domain. To accomplish this you must make an API call from your web app hosted in a different domain to Zoho's API domain (https://www.zohoapis.com). However, due to the CORS mechanism, the browser will block this API call.
Let us see what CORS is, how to enable it, and make it work.
Cross-origin resource sharing (CORS) is a browser security feature that restricts cross-origin HTTP requests initiated from scripts running in a browser. A cross-origin HTTP request is a request that is made to a different domain, sub-domain, port, or protocol. When non-simple HTTP requests are fired to a REST resource, CORS support needs to be enabled on that endpoint.
There are two types of cross-origin HTTP requests :
- Simple requests
- Non-Simple requests.
Simple HTTP Requests:
A simple request is a request that meets the below criteria.
- The request should use one of these methods GET, HEAD, POST.
- The headers allowed to be manually set (other than headers automatically set by the user agent) are Accept, Accept-Language, Content-Language, and Content-Type.
- The Content-Type header in the above criteria can only have the type/subtype as application/x-www-form-urlencoded, multipart/form-data, and text/plain.
- ReadableStream object is not allowed in the request.
- No event listeners are registered on the object returned by XMLHttpRequest.upload.
These requests will not trigger a CORS pre-flight. A pre-flight request is a CORS OPTIONS request that checks whether the CORS protocol is understood and the server is aware of using specific methods and headers.
For simple requests, the browser sends the header ORIGIN in the XMLHttpRequest to inform the target site about the request's origin. On the target site, the server compares the ORIGIN value with the allowed origins. If the source is allowed, the target site allows access to the resource to the requested site. Otherwise, the request is denied. All other cross-origin HTTP requests are non-simple requests. If your API's resources receive non-simple requests, you need to enable CORS support.
Non-Simple HTTP Requests:
Before the actual request is sent, a pre-flight request is sent to the target site. The browser sends the pre-flight request via the OPTIONS HTTP request method. The server sends the details about the target site such as the allowed methods and the allowed origins. After deciding whether the target site could return the information, the browser makes the actual GET/POST/PUT/DELETE request.
To enable CORS, the Rest API should be able to respond to the request with the following HTTP response headers.
HTTP response headers | HTTP request headers |
---|---|
Access-Control-Allow-Origin | Origin |
Access-Control-Expose-Headers | Access-Control-Request-Method |
Access-Control-Max-Age | Access-Control-Request-Headers |
Access-Control-Allow-Credentials | |
Access-Control-Allow-Methods | |
Access-Control-Allow-Headers |
Zoho enables the CORS headers for the HTTP requests generated by the registered Client Based OAuth Applications. ZCRM JS SDK acts as a middleware between Zoho CRM and your JS application. It makes the access and use of CORS-enabled CRM APIs facile. Invariably, HTTP requests and responses, token storage and refresh, firing CRM's APIs are taken care of by our SDK.
Please find the below instructions to use CORS in your web app.
Register your OAuth2.0 app as a 'Client-based Application'.
Include the CRM's JS SDK CDN URL similar to the way you include the necessary JS scripts (like jQuery, Bootstrap) in your HTML pages.
Copiedscript src="https://static.zohocdn.com/zohocrm/v2.0/sdk/3.0.0/sdk.js"
Initialize the SDK. Refer to this link for more initialization options.
Copiedlet logger = Logger.getInstance(Levels.ALL);
let environment = DataCenter.US.PRODUCTION();
let token = new OAuthBuilder()
.clientId("1000.UGPSX504F8BP77986BLW2E1HRXD5BH")
.scope("ZohoCRM.modules.ALL,ZohoCRM.settings.ALL")
.redirectURL("http://127.0.0.1:5501/redirect.html")
.build();
let sdkConfig = new SDKConfigBuilder()
.autoRefreshFields(true)
.cacheStore(true)
.pickListValidation(false).build();
(await new InitializeBuilder())
.environment(environment)
.token(token)
.initialize();
Handle OAuth2.0 Redirection handling. This is the HTML where the user will be redirected after the OAuth2.0 Authentication consent page. You need to place this HTML in your code repository and configure the same while configuring the OAuth2.0 app in Step 1. It is a one-time process. The script is available on this page. This places the token in the localStorage of the browser window, which will be transferred to the sessionStorage later by our JS SDK.
Now that all are set, you can invoke CRM's API from JS SDK. Sample codes are available here.
Copiedlet contactRolesOperations = new ZCRM.ContactRole.Operations();
let response = await contactRolesOperations.getContactRoles();
if(response != null) {
//Get the status code from response
console.log("Status Code: " + response.getStatusCode());
}
When our JS SDK's functions are invoked, if the current user is not authenticated, then the user will be taken to the OAuth2.0 authentication consent page. After the consent, the user will be redirected to the redirect.html page (as per step 4).
NOTE :
- When the tokens expire, our SDK will refresh them automatically. If needed, consent will be asked again.
- Click here to download the CORS-enabled web application built using our JS SDK. You can run this on a local server.