Kaizen #24 - CORS and the JS SDK

Kaizen #24 - CORS and the JS SDK

Hello everyone!
Welcome back to another week of Kaizen!
In this post, we will discuss the Cross-Origin Resource Sharing (CORS), and how it is used in Zoho CRM's JS SDK.

What is CORS?
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers in requests to allow web apps running in origin A, access to selected resources in origin B.
The below image depicts how CORS requests are served in a browser.


Here, in a web document hosted in domain-a.com, the main page, the layout CSS, and the image is served from the same domain (domain-a.com), while the canvas image is served from a different domain (domain-b.com). 
Therefore, the request to fetch the canvas image from domain-b.com is a cross-origin request controlled by CORS.

What requests use CORS?
  • Invocations of the XMLHttpRequest (XHR).
  • Web fonts so that servers can deploy TrueType fonts that can only be cross-site loaded and used by web sites that are permitted to do so.
  • Images/video frames drawn to a canvas using drawImage().
  • CSS shapes from images.

CORS Request Types
The browser decides the request type based on the request methods (GET/PUT/POST/DELETE) and the request headers.
The two types of CORS requests are
  1. Simple Requests
  2. Pre-flight requests
1. Simple Requests
  1. The browser sends the header ORIGIN in the XHR (XMLHttpRequest) to inform the target site about the request's origin.
  2. On the target site, the server compares the ORIGIN value with the allowed origins.
  3. If the source is allowed, the target site allows access to the resource to the requested site. Otherwise, the request is denied.

2. Pre-flight Requests
Before the actual request is sent, a pre-flight request is sent to the target site.
  1. The browser sends the pre-flight request via the OPTIONS HTTP request method.
  2. The server sends the details about the target site such as the allowed methods and the allowed origins.
  3. After deciding whether the target site could return the requested information based on this response, the browser makes the actual GET/POST/PUT/DELETE request.

Therefore, the server must send back the header Access-Control-Allow-Origin in the response header to serve simple and pre-flight requests appropriately.

Access-Control-Allow-Origin : [origin]
Example : Access-Control-Allow-Origin: https://www.example.com
This header allows only the website mentioned here to access the resources.
Here, https://www.example.com can access the resource on the target site, since it is explicitly allowed.
The server compares this value to the one sent in the ORIGIN header of the request, and accepts/rejects the request accordingly.

Access-Control-Allow-Origin : *
Example : Access-Control-Allow-Origin: *
The wildcard character (*) means that any site can access the resource in the target site. This practice is unsafe and hence, not widely used.

CORS and Zoho CRM JS SDK
Zoho CRM's JS SDK contains methods to invoke Zoho CRM's APIs that are CORS-enabled. All you have to do is register your JS app in Zoho Accounts Developer console  and authenticate it. 
You can then just use the methods available in our JS SDK in your code, and make API calls to Zoho CRM.

Prerequisites
  1. Your app must have the redirect.html page to which the access token is sent.
  2. The redirect.html page must contain the script to save the tokens in local storage based on the parameters sent after user authentication.
Before you can use the CRM APIs, you must
      a.  Register your app
      b. Authenticate your app

a. Register your app
  1. Go to https://api-console.zoho.com.
  2. Click ADD CLIENT
  3. Choose the client as Java Script and click CREATE NOW.
  4. Specify the client name, homepage URL of your app's UI, redirect URI (the HTML page of your application where you want the users to be redirected to after providing consent to your app), and the JavaScript domain.
  5. Click CREATE.
  6. Your client ID, client secret will be displayed under the Client Secret tab.

b. Authenticate your app
  1. Call the authorization URL from your HTML app.
    https://accounts.zoho.com/oauth/v2/auth?scope={scope}&client_id={client_id}&response_type=token&state=zohocrmclient&redirect_uri={path_to_the_redirect.html_of_your_app}
  2. Provide the necessary scopes, and the redirect_uri.
  3. The Zoho Accounts page prompts for user credentials. The user enters the credentials and may grant access for the entire session. 
  4. After the user grants access, Zoho Accounts redirects the user to the page you specified in the redirect_uri. You can see the access_token, grant_for_session as parameters to the redirect uri in the address bar.
    Example: javascriptDomainName/redirect.html?access_token={access_token}&grant_for_session=true|false
  5. The redirect.html file must run the script to store the access token of a particular user in local storage and use it while making API calls to Zoho CRM. This file is available in the attached ZIP of this post.
  6. Parse the access_token parameter to obtain the OAuth token.
  7. Note that the OAuthtoken expires every one hour. Generate a new one as and when required.

Note
  • You can find the sample JS app as an attachment to this post.
  • You can also download our JS SDK from the Github page.

After you download the ZIP, it opens the jssdktest folder that contains the below folders.
  • app - This folder contains the redirect.html file which holds the script to store and retrieve tokens from local storage.
  • index.html - The HTML file that renders the form where the user-entered details are captured to insert a lead in Zoho CRM. This file also calls the init() method to simultaneously initialize the SDK while the user submits the form.
  • js - this folder contains the zcrmsdk.js and the processData.js files. 
    zcrmsdk.js holds all the API methods.
    The processData.js file contains the script to initialize the SDK (init()), the action that happens when the user clicks the Submit button on the web page (submitData()) etc,.

Let us now see how CORS works while using the JS app.

Step - 1: User Redirection and SDK Initialization
The user visits your web page and the app redirects the user to Zoho Accounts with the client id, scopes, and the redirect URI that you have specified in the processData.js file.



The user enters the Zoho Credentials. Zoho Accounts prompts for user consent.
When the user clicks Accept, Zoho Accounts redirects the user to the URL you specified while registering your app. In our case, it is the path to the redirect.html file inside the app folder.
This step simultaneously initializes the SDK and runs the script to store the token.

Step - 2: redirect.html runs the script to store the access token
After the user grants access to the app, the access token is sent as a parameter in the address bar of the redirect URI.
The redirect.html invokes the setAccessToken() method and stores the token in local storage.
Here's the code snippet.

function setAccessToken() {
        var hashProps = getPropertiesFromURL();
        if(hashProps) {
            for( var k in hashProps) {
                if( hashProps.hasOwnProperty(k)) {
                    var key = ( k === 'access_toke' || k === 'access_token' ) ? 'access_token' : k;
                    var value = ( k === 'api_domain' ) ? decodeURIComponent(hashProps[k]) : hashProps[k];
                    localStorage.setItem(key, value);
                }
            }
        }
        setTimeout(function() { window.close(); }, 0);
    }
    setAccessToken();
You can also see the access token in the browser console under the Application tab.



Step-3: Display the Homepage of the app (index.html)
After the access token is obtained, the index.html page (the homepage URL you specified while registering) of your app is displayed.
The user enters the details in the form and clicks Submit.



Step-4: Invoke the submitData() method from the processData.js file
Clicking the Submit button invokes the submitData() method that contains the code to insert the lead in Zoho CRM with the details furnished in the form.
The code snippet is as follows.

function submitData()
{
    var firstName = document.getElementById("firstName").value;
    var lastName = document.getElementById("lastName").value;
    var email = document.getElementById("email").value;
    var company = document.getElementById("company").value;

    var dataObj = {'First_Name': firstName,'Last_Name': lastName, 'Email': email, 'Company': company};
    var input = {'module':'Leads', 'body':{'data':[dataObj]}};
        headers = {'Content-Type': 'application/json'};
       ZCRM.API.RECORDS.post(input).then(function(resp){
                var jsonData = JSON.parse(resp);
           window.location.replace(window.location.origin + "/view.html");
     //location.reload();
        });
}

Step-5: Make the cross-origin request to insert the lead
The method submitData() sets the headers and makes a function call to ZCRM.API.Records.post() which in turn, makes a CORS request to the Zoho CRM server.
You can see the request headers being set in the browser console under the Network tab.



As you can see, the header Access-Control-Allow-Origin contains the value as the JavaScript Domain.
When this domain and the one specified during app registration matches, the request goes through and the lead is inserted in CRM. Otherwise, the app receives the error.
Below is the screenshot after the lead is inserted in CRM.



The major advantage of using the JS SDK is that all APIs are available as JS functions,  and CORS code handling is already done. All you have to do is incorporate the requested methods in your app's code and make calls from the registered JavaScript domain.


We hope you found this post useful. Stay tuned for more!

Cheers!














    Access your files securely from anywhere

        Zoho Developer Community







                                  Zoho Desk Resources

                                  • Desk Community Learning Series


                                  • Digest


                                  • Functions


                                  • Meetups


                                  • Kbase


                                  • Resources


                                  • Glossary


                                  • Desk Marketplace


                                  • MVP Corner


                                  • Word of the Day



                                      Zoho Marketing Automation


                                              Manage your brands on social media



                                                    Zoho TeamInbox Resources

                                                      Zoho DataPrep Resources



                                                        Zoho CRM Plus Resources

                                                          Zoho Books Resources


                                                            Zoho Subscriptions Resources

                                                              Zoho Projects Resources


                                                                Zoho Sprints Resources


                                                                  Qntrl Resources


                                                                    Zoho Creator Resources



                                                                        Zoho Campaigns Resources


                                                                          Zoho CRM Resources

                                                                          • CRM Community Learning Series

                                                                            CRM Community Learning Series


                                                                          • Kaizen

                                                                            Kaizen

                                                                          • Functions

                                                                            Functions

                                                                          • Meetups

                                                                            Meetups

                                                                          • Kbase

                                                                            Kbase

                                                                          • Resources

                                                                            Resources

                                                                          • Digest

                                                                            Digest

                                                                          • CRM Marketplace

                                                                            CRM Marketplace

                                                                          • MVP Corner

                                                                            MVP Corner





                                                                              Design. Discuss. Deliver.

                                                                              Create visually engaging stories with Zoho Show.

                                                                              Get Started Now