/
Create a Self-Signed Certificate (Code)

Create a Self-Signed Certificate (Code)

This documentation provides a walkthrough demonstrating how to execute our self-signed certificate creation Apex Script via the Developer Console in your Salesforce org.

Admin access with Apex permissions is required to execute Apex Scripts from the Developer Console. Only users with administrative access should perform this activity. Please verify your access with your Salesforce Admin before executing this script.

APPLIES TO | CUNEIFORM FOR CRM FIELD AND DATA MANAGEMENT

 

Create a Self-Signed Certificate for our Connected App
Create a Self-Signed Certificate

Create a Self-Signed Certificate for our Connected App

FIVE MINUTEs

The APIs Cuneiform for CRM leverages (including Metadata, Tooling, and Query APIs) must be securely accessed. We use a self-signed certificate to accomplish this in alignment with Salesforce security recommendations and best practices.

About this Apex Script

We’ve created an Anonymous Apex script to create our Cuneiform for CRM: Self-Signed Certificate. This certificate will be attached to our Connected App and used to access Salesforce REST APIs securely. The script will:

  • Check if the Cuneiform for CRM: Self-Signed Certificate exists

  • If it exists – it does nothing and confirms to the user that the certificate was found

  • Otherwise – it attempts to create the self-signed certificate

The script will explain its outcome to the user. You can use this script to create the certificate programmatically. Alternatively, you can follow these steps to create the certificate declaratively via Salesforce Setup.

Execute the Anonymous Apex Script

Please copy this script to your clipboard. You can execute it against your Salesforce org via SFDX, your Salesforce IDE (ex. VSCode), or the Developer Console.

We provide guidance on executing this script via the Developer Console below. Open this expand-element to see the Anonymous Apex script – and copy it to your clipboard.

Open this expand-element to see the Anonymous Apex script – and copy it to your clipboard.

/** * ─────────────────────────────────────────────────────────────────────────────────────────────────┐ * Anonymous Apex to create our Self-Signed Certificate * Actions performed by this script: * * * [1:] Verify that our Cuneiform for CRM: Self-Signed Certifciate Exists * * [2:] If it does not -- then create the certificate * * This script was created to run before exercising the Control Panel to validate the installation. * It automates the configuration steps described in the Cuneiform for Salesforce product documentation * via https://jira-peernova.atlassian.net/wiki/spaces/CFCPD/pages/2598993921 * * See https://help.salesforce.com/s/articleView?id=sf.security_keys_creating.htm&type=5 * for details on the necessary object and security permissions required to create self-signed * certificcates and execute this script successfully. * ─────────────────────────────────────────────────────────────────────────────────────────────────┘ */ // Initialize local variables HttpRequest req; HttpResponse res; String retrieveCertificateXML; String certificateXML; // Initialize the visual formatting variables String spacer = ' '; String bdr = '---------------------------------------------------------------------------------------------------------------------------------'; // Initialize success messages (so we don't have to repeat them) String successLine1 = spacer + 'Nice work! Please visit'; String successLine2 = spacer + 'https://peernova.link/cuneiform/fdm/setup/step-002'; String successLine3 = spacer + 'to complete the next configuration step: Create the Connected App Permission-Set.'; System.debug(bdr); System.debug(spacer + 'Cuneiform for CRM: Field and Data Management: Certificate Creation Script'); System.debug(spacer + 'Create the Cuneiform for CRM: Self-Signed Certificate in Your Salesforce Org.'); // Initialize the ConnectedApp details String certificateYear = String.valueOf(Datetime.now().year() + 2); // Initialize the XML document used to create the certificate certificateXML = '<?xml version="1.0" encoding="UTF-8"?><env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><env:Header><SessionHeader xmlns="http://soap.sforce.com/2006/04/metadata"><sessionId>{0}</sessionId></SessionHeader></env:Header><env:Body><createMetadata xmlns="http://soap.sforce.com/2006/04/metadata"><metadata xsi:type="Certificate"><fullName>Cuneiform_for_CRM_Self_Signed_Certificate</fullName><caSigned>false</caSigned><encryptedWithPlatformEncryption>false</encryptedWithPlatformEncryption><expirationDate>{1}-01-01T00:00:00.000Z</expirationDate><keySize>4096</keySize><masterLabel>Cuneiform for CRM: Self-Signed Certificate</masterLabel><privateKeyExportable>true</privateKeyExportable></metadata></createMetadata></env:Body></env:Envelope>'; // Initialize the xml document containing the read-request details retrieveCertificateXML = '<?xml version="1.0" encoding="UTF-8"?><env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><env:Header><SessionHeader xmlns="http://soap.sforce.com/2006/04/metadata"><sessionId>{0}</sessionId></SessionHeader></env:Header><env:Body><readMetadata xmlns="http://soap.sforce.com/2006/04/metadata"><type>Certificate</type><fullNames>Cuneiform_for_CRM_Self_Signed_Certificate</fullNames></readMetadata></env:Body></env:Envelope>'; retrieveCertificateXML = String.format(retrieveCertificateXML, new String[] { UserInfo.getSessionId() }); // Initialize the httpRequest to verify the certificate exists req = new HttpRequest(); req.setEndpoint(Url.getOrgDomainUrl().toExternalForm() + '/services/Soap/m/60.0'); req.setMethod('POST'); req.setHeader('Content-Type', 'text/xml'); req.setHeader('SOAPAction', '""'); req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId()); req.setBody(retrieveCertificateXML); // Process the httpRequest res = new Http().send(req); // Check if the certificate already exists if (res.getBody().contains('<records xsi:type="Certificate"><fullName>Cuneiform_for_CRM_Self_Signed_Certificate</fullName>')) { System.debug(bdr); System.debug(spacer + 'We found a self-signed certificate with the API Name'); System.debug(spacer + '[Cuneiform_for_CRM_Self_Signed_Certificate] in this Salesforce org.'); System.debug(spacer); System.debug(successLine1); System.debug(successLine2); System.debug(successLine3); System.debug(bdr); } else { // Otherwise, let's create the certificate certificateXML = String.format(certificateXML, new String[] { UserInfo.getSessionId(), certificateYear }); // Apply the certificate details to the request and process it req.setBody(certificateXML); // Process the httpRequest res = new Http().send(req); // Check the response and audit / output the results to the end-user if (!res.getBody().contains('<success>true</success>')) { System.debug(bdr); System.debug(spacer + 'We were unable to create the Cuneiform for CRM: Self-Signed Certificate. Please review the error response for details.'); System.debug(spacer + 'Metadata API Error Response:'); System.debug(spacer); System.debug(res.getBody().mid(res.getBody().indexOf('<errors>'), res.getBody().indexOf('</errors>') - (res.getBody().indexOf('<errors>') - 9))); System.debug(spacer); System.debug(spacer + 'Please review Metadata API Error Response, and try again. Verify that you have access'); System.debug(spacer + 'and permission to create Metadata via the Metadata API, and that the Cuneiform for CRM'); System.debug(spacer + 'Self-Signed Certificate does not already exist in your Org.'); } else { System.debug(spacer + 'The Self-Signed Certificate was successfully created.'); System.debug(spacer); System.debug(successLine1); System.debug(successLine2); System.debug(successLine3); } System.debug(bdr); }

Execute Our Certificate Creation Apex Script

Follow these steps to open the Developer Console and execute our Cuneiform for CRM: Self-Signed Certificate creation script. This script will create a self-signed certificate in your Salesforce org.

  1. Copy the Anonymous Apex Script to your clipboard.

  2. Log into your Salesforce org – and launch the Developer Console.

image-20240611-203112.png
Launch the Developer Console via the Gear Icon used to Open Salesforce Setup.
  1. Launch the Execute Anonymous window from within the Developer Console. The Execute Anonymous Window modal is available on the Debug menu.

image-20240611-203405.png
Open the Execute Anonymous window via the Debug menu in the Developer Console.
  1. Paste the Anonymous Apex script in the Anonymous Apex Window.

  2. Execute the Anonymous Apex Script by clicking on the Execute button.

image-20240910-175144.png
Pase the Anonymous Apex Script into the Apex Code window – and click Execute.
  1. Open the log file generated by the script – and filter on the debug results to view the output.

image-20240611-201749.png
Open the generated log file – and enable the Debug filter to view the script output.
  1. View the debug output and verify that the script created the self-signed certificate.

image-20240910-175317.png
Verify from the script output that the Self-Signed Certificate was successfully created.
  1. Navigate to Certificate and Key Management in Salesforce Setup and verify that the certificate was successfully created in your Salesforce org.

image-20240910-002332.png
Verify that the Self-Signed Certificate was successfully created in Salesforce Setup.
  1. Click on the certificate label to view its record detail page. Click on the Download Certificate button to download a local copy (you’ll need it to enable digital signatures in the Connected App).

image-20240910-002600.png
Download a copy of the Self-Signed Certificate and store it securely for future use.

You will need a local copy of the self-signed certificate for the final configuration step: attaching the certificate to your configured Connected App. Please confirm that you have downloaded a copy of the certificate before moving onto the next configuration step.


Nice work! Once you’ve verified the certificate was successfully created and have downloaded a copy of the certificate to your local workstation, you can move on to the next configuration step, creating the Connected App permission set.