1

I'm trying to make use of Salesforce Named Credentials to securely store the API Key and call endpoint accordingly.

I tried to pass a custom API Key to an endpoint as below.

HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('callout:API_endpoint'+'/customers');
req.setHeader('Authorization', '{!$Credential.Password}');   // Password contains 'Basic <<Base64EncodedKeyValue>>'
HTTPResponse res = new HTTP().send(req);
System.debug('res '+res.getBody());

But it's throwing the 401 - Unauthorized response.

  1. Is there a way to check the final request code e.g. like in postman request code?
  2. If I use the hard-coded http request attributes + remote site (without using named credential), it's working perfectly. Is it possible to override Authorization ? and How do I use Named credential to override Authorization header correctly?

Much appreciate any help/comment/thoughts on this? Cheers!

1
  1. By pointing your callout to a service that logs/echoes the request. ngrok is one popular option that proxies/tunnels a request.
  2. When setting up the Named Credential, do this:
  • Select Named Principal as the Identity Type
  • Select Password Authentication as the Authentication Protocol.
    • Set the Username field to any (bogus) value. It will not be used.
    • Compose the value of Password field by concatenating string 'Basic ' (note the extra space) with a base64-encoded value of your plaintext password.
  • Confirm that Generate Authorization Header is NOT checked
  • Confirm that Allow Merge Fields in HTTP Header IS checked
4
  • Thanks @identigral, In SF both username and password are required. I did add them manually hoping to override SF Auth header because I got only Key, Is it possible to omit the username field in Namedcredentials? I used a fake text because it's mandatory. – Pasan Eeriyagama Oct 29 '20 at 5:51
  • @Pasan Eeriyagama See updated answer – identigral Oct 29 '20 at 6:04
  • Oh thanks! Found Generate Authorization Header was checked. After unchecking it worked perfect. I tried the Encoding merge field here, but it doesn't work as it's just encoding the text 'Credential.password' instead content of that at runtime. So it worked fine, but still needed to store the encoded key in password field. I'm marking this as answer, please remove the Encoding as it's not working. Cheers! – Pasan Eeriyagama Oct 29 '20 at 6:18
  • 1
    @Pasan Eeriyagama Fixed, thank you. – identigral Oct 29 '20 at 7:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.