Named Credentials in Salesforce with Example

Named Credentials in Salesforce is used to specify the endpoint and its required authentication parameters in a single definition. By using Named Credentials, we don’t have to specify callout endpoints in Remote Site Settings. And we don’t even have to handle Authentication in code. Named Credentials will take care of all. It is more secure and we can do the OAuth Implementations flawlessly. Let’s implement Named Credentials in Salesforce with an example. We will also look into the common error we get while implementing Named Credentials i.e, invalid_header_type or invalid_auth_header.

We will also cover why most of the Salesforce developers get below error when they implement Named Credential for the first time.

[{"message":"INVALID_HEADER_TYPE","errorCode":"INVALID_AUTH_HEADER"}]

Implementation

In this implementation, we will use the Named Credentials in Salesforce to call the External system to get a list of Animals.

Named Credentials in Salesforce with Example
Named Credentials in Salesforce with Example

Type Named Credentials in the Quick Find box and click on Named Credentials. As we are hitting Animals API, enter AnimalCreds in Label and Name. In URL, enter below URL:

https://th-apex-http-callout.herokuapp.com/animals

If we enter this URL in Browser, we will get below list of Animals in response.

{"animals":["majestic badger","fluffy bunny","scary bear","chicken"]}

For Identity Type, select Anonymous as it does not require any type of Authentication. Other options are Per User and Named Principal. A Named Principal applies the same credential or authentication configuration for the entire org, while Per User authentication provides access control at the individual user level. Authentication Protocol will be No Authentication for Anonymous Identity Type.

A Named Credential Authentication Protocol supports basic password authentication, OAuth 2.0, JWT, JWT Token Exchange, and AWS Signature Version 4. We will cover this in the latter part of this post.

Select Generate Authorization Header checkbox and leave Allow Merge Fields in HTTP Header and Allow Merge Fields in HTTP Body fields unchecked and click Save. We can check these fields to enable the Merge Fields in HTTP Header and Body, which is not required in our case. The Named Credential in Salesforce will look something like below:

Named Credentials in Salesforce with Example
Named Credentials in Salesforce with Example

Use Named Credentials in Apex

Without Named Credentials in Salesforce, we have to add the endpoints in Remote Site Settings, provide the endpoint, Authentication Headers in HTTP Request, and provide the HTTP method name. By using Named Credentials, we just need to provide the Named Credential name and method. Named Credentials will take care of the rest.

Provide the Named Credentials name in setEndpoint() method like:

request.setEndpoint('callout:AnimalCreds');

Where AnimalCreds is the name of Named Credentials that we just created. We can also provide the parameters to Named Credential like callout:AnimalCreds?q=something or callout:AnimalCreds/1/.

Animals.apxc

public class Animals {
    
    @AuraEnabled
    public static String fetchAnimals(){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        
        // Provide the Named Credentials
        request.setEndpoint('callout:AnimalCreds');
        request.setMethod('GET');        
        HttpResponse response = http.send(request);
        if (response.getStatusCode() == 200) {
            return response.getBody();
        }
	return null;
    }
}

Create a Lightning Component to call fetchAnimals() apex method which will hit the Animals web service. Add button in Lightning Component to call this apex method. Iterate through the list of Animals received from the response to display it on UI.

AnimalCmp.cmp

<aura:component controller="Animals" implements="flexipage:availableForAllPageTypes">
    <!-- attributes -->
    <aura:attribute name="data" type="List"/>
    
    <lightning:card title="Named Credentials - Basic Implementation">
        <div class="slds-p-left_x-small">
            <lightning:button label="Get Animals from External System" onclick="{!c.getAnimals}" /> <br/><br/>
        
            <!-- Display list of Animals -->
            <p style="font-weight:bold">List of Animals:</p>
            <ul class="slds-list_dotted">
                <aura:iteration items="{!v.data}" var="animal">
                    <li>{!animal}</li>
                </aura:iteration>
            </ul>
        </div>
    </lightning:card>

AnimalCmpController.js

({
    getAnimals: function (component, event, helper) {
        helper.getAnimalsHelper(component, event, helper);
    }
});

AnimalCmpHelper.js

({
	getAnimalsHelper : function(component, event, helper) {
		var action = component.get("c.fetchAnimals");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var results = response.getReturnValue();
                if(results != null){
                    component.set("v.data", JSON.parse(results).animals);
                }
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
        $A.enqueueAction(action);
	}
})

Named Credentials using Password Authentication

In the previous example, we called the external web service which does not need any Authentication. For the web services which require some type of Authentication like username and password, we have to use Named Credentials using Password Authentication as the Authentication Protocol. This type of authentication is called Basic Authentication.

If we want to handle this without Named Credential, we have to save the username and password in either Custom Setting or Custom Metadata Type. In the worst case, we have to hard code it in Apex class. Then we need to encode it using base64Encode() to add it in the header like below:

String username = 'username';
String password = 'password';  
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' +
EncodingUtil.base64Encode(headerValue);
request.setHeader('Authorization', authorizationHeader);

To use Named Credentials, follow the same process implemented earlier but this time, select Per User or Named Principal as Identity Type based on the requirement. Select Password Authentication as the Authentication Protocol. And enter the Username and Password which will be used to authenticate against a web service.

Named Credentials using Password Authentication
Named Credentials using Password Authentication

This is all we need to do. We don’t have to make any changes in the Apex class. Named Credential mentioned in the setEndpoint(‘callout:YourNamedCred’) will take care of Authentication. This is how we can use Named Credentials using Password Authentication. You can implement this by using the web service that requires Password Authentication. You just need to enter the Endpoint in URL, provide the username and password and that is all.

Also Read:

INVALID_HEADER_TYPE and INVALID_AUTH_HEADER

[{"message":"INVALID_HEADER_TYPE","errorCode":"INVALID_AUTH_HEADER"}]

Most of the Salesforce developers face INVALID_HEADER_TYPE or INVALID_AUTH_HEADER error while trying to implement Named Credentials in Salesforce. Most of the time, we implement the web service in Salesforce Org using Rest Resource and we try to call it from another Salesforce Org. But the issue here is that Salesforce as a provider does not support Password Authentication. Hence we usually get this error. If the web service is written in Salesforce org, we must use OAuth 2.0 or other authentication methods.

OAuth implementations are complicated, but with Named Credentials in Salesforce, it is very easy to implement and maintain. In the next post, we will implement OAuth 2.0 to authorize our user to call the web service implemented in another Salesforce org.

Now that you know the basics, you can check advanced topics relatd to Salesforce Named Credentials:

If you don’t want to miss new implementations, please Subscribe here.

This is how we can use Named Credentials in Salesforce. If you want to check more implementations in Salesforce, you can check it here. Check official Salesforce documentation about Named Credentials here. See you in the next implementation.

4 thoughts on “Named Credentials in Salesforce with Example”

  1. Hi Niks,

    I am trying to connect with Curity as Identity Provider and need to connect with Salesforce as client and Microservices API using per user authentication.

    Please connect .This is very critical ticket.

    Reply

Leave a Comment