Showing posts with label Named Credential salesforce; benefits of named credentials. Show all posts
Showing posts with label Named Credential salesforce; benefits of named credentials. Show all posts

Sunday, March 19, 2023

What are Named Credentials in Salesforce? What are its Benefits

Let us understand what are Named Credentials in Salesforce and what are its Benefits

Using Named Credential, we can make call out to external system without supplying username or Password
A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. To simplify the setup of authenticated callouts, specify a named credential as the callout endpoint.

Why Avoid Hardcoding Credentials :

  1. It is a Maintenance nightmare. Having Credentials hardcoded means you have to deploy the changes every single time like when your password changes or expires.
  2. It is also difficult to maintain changes in a different environment
  3. Not very secure.

Benefits of using Named Credentials :

  1. Authentication is done by Salesforce and you need not to worry about that.
  2. Easy for admins to maintain.
  3. Secure storage of credentials.
  4. No need to create a Remote Site Setting if using a Named Credential.
  5. The callout is easier to maintain. No hard coding involved.

Apex HTTP Callout Without Named Credential:

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:

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);

Mostly Viewed