I have a GET request I want to manage but Authorization Header is not working if I retrieve username and password from Named Credential.

String username = '{!$Credential.UserName}';
String password = '{!$Credential.Password}';
request.setEndpoint('callout:NamedCredential/scan/' + EncodingUtil.urlEncode(customMetadataLIST[0].AccessCode__c, 'UTF-8'));
request.setHeader('Authorization', 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf(username + ':' + password)));

If I put username and password directly is working fine and I don't know what am I doing wrong.

1 Answer 1


Check the "Generate Authorization Header" on the Named Credential, and Salesforce will do it for you automatically, no setHeader method call required.

Alternatively, just set the following value:

request.setHeader('Authorization', '{!$Credential.AuthorizationHeaderValue}');

It will automatically generate the correct Basic encodedusername:encodedpassword for you.

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.