For every API I'm consuming from Salesforce so far, I'm using the Client Credentials Grant for everything that's just between servers (= no user involved). It seems that Salesforce itself does not support the Client Credentials Grant at all. If so, why? And is my assumption even correct? What would be an alternative - and why?
All transactions in Salesforce are user-based. User access determines field level and record level access, page layouts, and so on. There's absolutely no way to perform an action as an anonymous "non-user." Even automated processes use an "Automated User" user for logging actions against. This is related to the auditing capabilities of Salesforce. The typical alternative is to log in as an admin or integration user.
It's correct that you cannot perform a Client Credentials grant, but headless authentication, scoped to a user, is pretty easy. You can accomplish this with the OAuth 2.0 JWT Bearer Token Flow
- Create a Connected App
- Generate an X509 Cert and upload the cert to the Connected App
- Set the connected app policy to Admin approved users are pre-authorized
- Give one or more of your users access to the app via Permission Sets or Profiles.
- Make sure your external application has access to the X509 private key. Take care to store this securely with your application.
- Generate a JWT using the user you'd like to authenticate with. You'll set their username to the
subproperty. You'll sign it with the X509 private key.
- Post it to the token endpoint with
This will return you an access token. Find a library in your preferred language to help with the construction and signing of your JWT. More details in the link above.
The JWT Bearer Token Flow is still a very valid alternative for server-to-server communication, but since the Winter '23 release the Client Credential Flow is now also supported by Salesforce.
The Client Credential Flow is safer than the Username-Password flow because it doesn't transmit actual user credentials, and is simpler than the JWT Bearer Token Flow because it doesn't need key management.
The call would be a simple POST to the
token endpoint, providing the client id and secret and
client_credentials as grant type in the body:
POST /services/oauth2/token HTTP/1.1 Host: MyDomainName.my.salesforce.com grant_type=client_credentials& client_id=*******************& client_secret=*******************
Another option would be to Base64 encode the client id and secret in a Basic Authentication header:
POST /services/oauth2/token HTTP/1.1 Host: MyDomainName.my.salesforce.com Header: Authorization: Basic TXlDbGllbnRJRDpNeUNsaWVudFNlY3JldA== grant_type=client_credentials
Salesforce returns an access token based on the executing user and the scopes that you configure in the Connected App
The documentation can be found here: OAuth 2.0 Client Credentials Flow for Server-to-Server Integration