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.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 Answer 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
  • 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. Oct 29, 2020 at 5:51
  • @Pasan Eeriyagama See updated answer
    – identigral
    Oct 29, 2020 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! Oct 29, 2020 at 6:18
  • 1
    @Pasan Eeriyagama Fixed, thank you.
    – identigral
    Oct 29, 2020 at 7:21
  • 1
    @NZ Dev API Key is a password-only authorization primitive. No, it won't be true for any endpoint.
    – identigral
    Jan 7, 2022 at 15:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .