Named Credentials — A turning point for callouts in Apex

14 Jan 2016

Hey Guys,

I did some hands on Named Credentials (feature released by Salesforce two releases back) recently and want to share my knowledge.

What are Named Credentials?

  1. Specifies the URL of a callout endpoint and its required authentication parameters(methods & urls) with point & click.
  2. Can be seen as advance version of remote site settings in one scenario but it has totally different purpose. Remote site settings are not required for this.
  3. Named credentials handles all authentication requirements like headers to be set etc.
  4. It is an alternate of using remote site settings with apex code handling. It is much more secure.
  5. Supports two types of authentication protocols for now : Basic Authentication(Password authentication) or OAuth.
  6. Can be configured easily if Authentication needs to be done in User Context or Admin Context

OAuth Protocol:

This requires a proper setup of Auth provider in salesforce with configurations like consumer key, consumer secret, callback url.

We can also connect two orgs with this method.To connect with another salesforce, connected app needs to be created in one org & Auth provider & named credentials need to be configured in another.

Below are some screenshots displaying same:

Password protocol:

This require user’s username & password of external system to be connected and Salesforce will take care of rest. This is works on basic authentication where username & password is encoded to base64 & set it in header in every request.

PS: This method cannot be used to connect two salesforce orgs as Salesforce don’t provide Basic Authentication method to authenticate

Anonymous:

This is same like remote site setting. Add an url and make a callout, no authentication needed.

Very Important:

Both OAuth & password protocol methods needs HTTPS urls and cannot accept HTTP. Only Anonymous protocol can accept HTTP url.

Brief about callout options

There can be different scenarios for authentications. For example, some remote endpoints require security tokens or encrypted credentials in request headers. Some remote endpoints expect usernames and passwords in XML or JSON message bodies. Customize the callout headers and bodies as needed.

Salesforce admins can use following options to tackle these scenarios:

Generate Authorization Header Deselect this option only if one of the following statements applies.

  • The remote endpoint doesn’t support authorization headers.
  • The authorization headers are provided by other means. For example, in Apex callouts, the developer can have the code construct a custom authorization header for each callout.

This option is required if you reference the named credential from an external data source.

Allow Merge Fields in HTTP Header Allow Merge Fields in HTTP Body In each Apex callout, the code specifies how the HTTP header and request body are constructed. For example, the Apex code can set the value of a cookie in an authorization header.

These options enable the Apex code to use merge fields to populate the HTTP header and request body with org data when the callout is made.

These options aren’t available if you reference the named credential from an external data source.

Following are some examples to use merge fields with global variable {!$Credentials} (new global variable for named credentials):

{!$Credential.Username} {!$Credential.Password} Username and password of the running user. Available only if the named credential uses password authentication.

// non-standard authentication req.setHeader(‘X-Username’, ‘{!$Credential.UserName}’); req.setHeader(‘X-Password’, ‘{!$Credential.Password}’);

{!$Credential.OAuthToken} OAuth token of the running user. Available only if the named credential uses OAuth authentication.

req.setHeader(‘Authorization’, ‘OAuth {!$Credential.OAuthToken}’);

{!$Credential.AuthorizationMethod} Valid values depend on the authentication protocol of the named credential

  • Basic — password authentication
  • Bearer — OAuth 2.0
  • null — no authentication

{!$Credential.AuthorizationHeaderValue} Valid values depend on the authentication protocol of the named credential.

  • Base-64 encoded username and password — password authentication
  • OAuth token — OAuth 2.0
  • null — no authentication

{!$Credential.OAuthConsumerKey} Consumer key. Available only if the named credential uses OAuth authentication.

Apex Code to use Named Credentials

HttpRequest req = new HttpRequest(); req.setEndpoint('callout:My_Named_Credential/some_path'); req.setMethod('GET'); Http http = new Http(); HTTPResponse res = http.send(req); System.debug(res.getBody());

Happy Coding!

Labels: ForceDotCom, Callouts, Salesforce, Apex


Originally published at blog.lkatney.com on January 14, 2016.