Using Named Credentials and Auth Provider to manage security token for APEX Callout to an OAuth 2.0 REST API

I’m trying to do an APEX Callout to a OAuth 2.0 secured REST API

This is the API
https://developers.pandadoc.com/v1/reference#authentication-process

I want to use something to manage the security token rather than write APEX code to do it. And according to this that’s what Named Credentials are for. Specifically this passage:

Salesforce manages all authentication for callouts that specify a
named credential as the callout endpoint so that you don’t have to.
You can also skip remote site settings, which are otherwise required
for callouts to external sites, for the site defined in the named
credential.

The problem I have is I’m trying to use an Auth Provider but there’s no OAuth 2.0 option so I’m using OpenID. Which if I understand correctly rides on OAuth 2.0. I’m not sure what the “Redirect URI” should be from the PandaDoc API side. I’m using the “Callback URL” but it’s not working.

I have the whole flow working in Postman from the Collection PandaDoc publishes. They also have a video showing the Postman setup. I’m able to use the builtin Postman OAuth 2.0 Authorization to get the Access Token and make successful calls to the PandaDoc API.

In my case I’m calling PandaDoc API but this would be useful for anyone calling out from Salesforce to any OAuth 2.0 secured API. I didn’t find any good examples of how to make an Apex Callout to an OAuth 2.0 REST API.

Answer

Named credential does have oAuth 2.0, the problem is with the Auth Provider. (I believe)

  • Select Identity Type as “Named Principle”
  • Then Select oAuth 2.0 as the Protocol

You will need to set up the AuthProvider as well and if they do not support OpenID Connect then you will need to create a custom auth provider according to the HELP document. I do not think it is a trivial exercise

The steps to do so are pretty detailed but one of the items in the registration class that is relevant to your question is quoted below

Existing User Linking URL—Use to link existing Salesforce users to a third-party account. The user opens this URL in a browser, signs in to the third party, signs in to Salesforce, and approves the link

Someone please correct me if I am wrong in that since the desire here is to get a token for the external system a custom provider may need to be implemented.

Attribution
Source : Link , Question Author : HungryPipo , Answer Author : Eric

Leave a Comment