Glen Mazza's Weblog

https://glenmazza.net/blog/date/20210328 Sunday March 28, 2021

Making Salesforce CRM API calls with Postman

Salesforce's Mohith Shrivastava's second Connected App tutorial shows how the JWT Bearer Token Flow can be used with Postman to obtain access tokens. Separately, SFDCStop shows how to use an access token to retrieve data from Salesforce. Summary of the process for getting an access token via JWT Bearer Token flow is given below, along with the alternative Username-Password flow.

Obtaining Access Token via JWT Bearer Token Flow

Mohith's second tutorial largely follows the Trailblazer documentation for creating the JWT necessary for obtaining an access token. First, within Postman, open a POST request to https://test.salesforce.com/services/oauth2/token (or login.salesforce.com for production) with two query attributes, grant_type hardcoded to urn:ietf:params:oauth:grant-type:jwt-bearer and assertion with a value that can be generated at JWT.io as follows:

  1. Place {"alg":"RS256"} in the JWT header.

  2. Place the following in the JWT payload, updating the iss value with the Client ID of the connected app, the aud value (should be either https://test.salesforce.com for sandbox instances, https://login.salesforce.com for all others, including developer instances), the sub with the Salesforce resource owner (the user ID, usually expressed as an email), and exp value being the ten-digit current UNIX timestamp. Ensure there are no spaces or carriage returns in the payload:

    {"iss":"--client id--","sub":"--salesforce user--","aud":"https://test.salesforce.com","exp":"1616865336"}

    You may also wish to add a "jti" field (JWT ID), the value of which can be a randomly generated UUID. As stated in the Trailblazer documentation linked above, if a "jti" field is added, Salesforce will make sure the JWT hasn't been used to make a prior access token request, serving as a guard against replay attacks. If it has been used, it will return a 400 response code with message { "error": "invalid_request", "error_description": "jti already in use"}.

  3. Finally, in the Verify Signature portion, as generated in the previous tutorial, place the PublicCert.crt contents and the private key found in key.pem (including the BEGIN/END delimiters) in the corresponding boxes. JWT.io should report "Signature Verified", upon which you can copy the left-side as the assertion value into the Postman call. Make the call and you should get an access token in response.

    BearerTokenRequest

Obtaining Access Token via Username-Password Flow

This process is much more straightforward as no keys are used. As shown in the Salesforce documentation, you can simply make a POST request with the following five query parameters: grant_type, client_id, client_secret, username, and password.

PostmanViaUsernamePwd

Making Salesforce calls using the Access Token

As demo'ed in the SFDCStop video, can create a GET request to say https://yoursalesforceinstance.salesforce.com/services/data/v50.0/query?q=SELECT+Name,Type+FROM+Account. Under the Authorization tab, select "Bearer", copy-and-paste the access token in, and make the API call.

SOQLQuery

More information on SOQL calls are available here.

Posted by Glen Mazza in Salesforce CRM at 03:00AM Mar 28, 2021 | Tags:  salesforce  postman  oauth2 | Comments[0]

https://glenmazza.net/blog/date/20210321 Sunday March 21, 2021

Creating a Salesforce Connected App

Salesforce Connected Apps provide the conduit for data transfers between Salesforce and third-party apps. Salesforce's Mohith Shrivastava offers four-part series on Connected Apps, roughly four hours of instruction in total, helpful for visual walk-through of configuration. Below are simple steps I've followed for configuring a Connected App, but as always the official documentation should be at least reviewed to make sure all security matters are properly taken care of.

Creating credentials to access a Connected App.

The OAuth Authorization Flows section in the Salesforce Trailblazer documentation details the various methods (or "flows") available for working with Salesforce data externally. Below lists configuration for two of the flows usually best for server-to-server integration, i.e., without an active user logging in and activating the processes. For this use case, Salesforce recommends creating an integration user. Instructions here and here seem to best for creating an integration user. However, the profile options for choosing "API Enabled" and "API Only User" (i.e., user can not directly log into Salesforce) appear not to be under a "Administrative permissions" section anymore but under the System: System Permissions option when one creates the integration user's profile.

  • OAuth 2.0 JWT Bearer Flow: Accessing the application using a public/private key pair. Here, the public cert is uploaded to the Salesforce connected app, while the requests are signed by the client using the private key. The Connected App relies on the successful decrypting of the message to confirm the request is coming from the client. In this case, the user's login and connected app consumer key are needed by the client, but not the user's password or the connected app client secret.

    A locally-made key pair is sufficient for this access technique, I've used a combination of the Java keytool and OpenSSL for this. Steps:

    1. Create a Java PKCS12 keystore using the following command. Keystore passwords here don't matter as they will soon be discarded (keys will be worked with directly). Note that validity given below is in days, whatever value you choose, note the key will need to be replaced with it expires:

      keytool -genkeypair -keyalg RSA -sigalg SHA1withRSA -validity 1095 -storepass mypassword -storetype PKCS12 -keystore tempKeystore.p12 -alias myappkey
    2. Create a public certificate to be uploaded to the Salesforce Connected App:

      keytool -export -rfc -keystore tempKeystore.p12 -storepass mypassword -file PublicCert.crt -alias myappkey
    3. As for the public key itself, it is not needed for making Salesforce calls, but can be obtained if desired via:

      openssl x509 -pubkey -in PublicCert.crt -text -noout
    4. Finally, extracting the private key from the keystore. The private key needs to be kept secure as anyone with it can access the Salesforce Connected App, once the latter is configured with its public cert.

      openssl pkcs12 -in tempKeystore.p12 -passin pass:mypassword -nodes -nocerts -out key.pem
      
  • OAuth 2.0 Username-Password Flow for Special Scenarios: Obtaining access tokens using the resource owner's username and password instead of X.509 key pair. Salesforce does not ordinarily recommend this flow, quote: "Use it only if there’s a high degree of trust between the resource owner and the client, the client is a first-party app, Salesforce is hosting the data, and other grant types aren’t available. In these cases, set user permissions to minimize access and protect stored credentials from unauthorized access."

    If you're heavily using Postman to obtain access tokens, this method is much easier and faster than manually creating JWT bearer tokens, of course be careful though that the user and client credentials don't get exposed to others who shouldn't have them.

Salesforce Connected App Configuration
  1. Log into Salesforce and click the gear on the upper right side to choose Setup (illustration below). Once the setup window appears, on the left-side search box search and select "App Manager". Once App Manager is up, select the New Connected App button on the right-side.

    SCA_SetupButton

    SCA_NewConnApp

  2. Click on the "Enable OAuth Settings" checkbox to place in configuration similar to the below. See the official documentation for an explanation of options available, also note the refresh_token role granted below would be unneeded for either of the two flows above (neither use refresh tokens). If using the Bearer Flow, be sure to click on "Use Digital Signatures", place the public key generated earlier into a file and upload. The callback URL will be ignored for either of the two flows, but a value needs to be provided regardless. When done, hit “Save” at the top, and then the “Manage” button, and then “Edit Policies” (covered in next step).

    SCA_OAuthSettings
  3. On the Policies page, here is where you may wish to add IP Address restrictions to limit from where approved clients may call the application. Click Save and scroll to the Profiles section (next step).

    SCA_OAuthPolicies

  4. For profiles, add the profile of the User being used to make the Salesforce calls. If an Integration User profile was created as suggested above, for example, choose that. Make sure the user associated with the calls is part of that profile.

  5. Back in App Manager, in the table of apps, go to the last column of the new connected app and choose View. As mentioned earlier, just the consumer key will be needed for the Bearer flow, but both that and the consumer secret for the Username-Password flow. As with the private key in the Bearer flow, make sure the client secret is stored confidentially, should it get exposed the connected app should be deleted and a new one which will have a different consumer key and secret created.

Posted by Glen Mazza in Salesforce CRM at 03:00AM Mar 21, 2021 | Tags:  salesforce  oauth2 | Comments[0]


Calendar
« December 2024
Sun Mon Tue Wed Thu Fri Sat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Today
About Me
Java Software Engineer
TightBlog project maintainer
Arlington, Virginia USA
glen.mazza at pm dot me
GitHub profile for Glen Mazza at Stack Overflow, Q&A for professional and enthusiast programmers
Blog Search


Blog article index
Navigation
About Blog
Blog software: TightBlog 4.0.0
Application Server: Tomcat
Database: MySQL
Hosted on: Linode
SSL Certificate: Let's Encrypt
Installation Instructions