Site icon WedgeCommerce

Named Credentials Basics

Banner

Salesforce introduced Named Credentials in the Spring’15 release. A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. Salesforce manages all authentication for Apex callouts that specify a named credential as the callout endpoint so that your code does not have to. If you instead specify a URL as the callout endpoint, you must register that URL in your org’s remote site settings and handle the authentication yourself. For example, for an Apex callout, your code handles authentication, which can be less secure and especially complicated.

It offloads the storage of credentials and authentication to a declaratively controlled process.  You can also skip remote site settings, which are otherwise required for callouts to external sites, for the site defined in the named credential.

 

Why Avoid Hardcoding Credentials :

 

Benefits of using Named Credentials :

 

Define Named Credentials :

From Setup, enter Named Credentials in the Quick Find box, and then select Named Credentials.

Click New Named Credential, or click Edit to modify an existing named credential.

Complete the fields –

  1. Anonymous: No identity and therefore no authentication.
  2. Per User: Use separate credentials for each user who accesses the external system via callouts.
  3. Named Principal: Use the same set of credentials for all users who access the external system from your org.

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

  1. The remote endpoint doesn’t support authorization headers.
  2. 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.

Example :

Apex HTTP Callout Without Named Credential:

Basic Auth Example The Traditional Way –

HttpRequest req = new HttpRequest();

req.setMethod(‘POST’);

req.setEndpoint(‘https://example .com/path/my/api’);

String username = ‘username’;

String password = ‘password’;

//Add basic authentication header to the callout

Blob headerValue = Blob.valueOf(username + ‘:’ + password);

String authHeader = ‘BASIC ‘ + EncodingUtil.base64Encode(headerValue);

req.setHeader(‘Authorization’, authHeader);

Http h = new Http();

HttpResponse response = h.send(req);

System.debug(‘response-‘ + response);

 

Apex HTTP Callout With Named Credential:

Basic Auth Example With Named Credentials –

HttpRequest req = new HttpRequest();

req.setMethod(‘POST’);

req.setEndpoint(‘callout:Sample_API/some_path’);

//No need to manually set any headers here. Salesforce will add this for us automatically.

Http http = new Http();

HTTPResponse response = http.send(req);

System.debug(‘response-‘ + response);

 

Exit mobile version