Named Credential – using a merge field

apexcalloutnamedcredentials

Im facing issues trying to generate the auth header in Apex when using Named Credentials.

Unfortunately I cannot use the standard Named Credential approach (auto header generation) as I have to embed a session id in the header.

Named Credential setup

Blob authHeaderValue = Blob.valueOf('{!$Credential.Username}' + ':' + sessionId);
HttpRequest request = new HttpRequest();
request.setMethod('POST');
request.setEndpoint('callout:endpointexample');
request.setHeader('Content-Type', 'application/json');
request.setHeader('Authorization', 'Basic' + ' ' +  EncodingUtil.base64Encode(authHeaderValue));
Http http = new Http();
HTTPResponse res = http.send(request);

If I hardcode the username it works fine so assuming {!$Credential.Username} is the issue here.

Best Answer

Named Credential acts as a runtime proxy. The proxy receives your HTTP request then searches its body or headers for the merge field as a literal string. If NC doesn't find the field, it won't interpolate (merge) it:

This works: request.setHeader('X-Username', '{!$Credential.Username}');

This also works (assuming Generate Authorization Header is unchecked): request.setHeader('Authorization', 'Bearer: {!$Credential.Username}');

This does not work:

Blob authHeaderValue = Blob.valueOf('{!$Credential.Username}' + ':' + sessionId);
request.setHeader('Authorization', 'Basic ' + EncodingUtil.base64Encode(authHeaderValue));

...nor does this:

Blob authHeaderValue = Blob.valueOf('{!$Credential.Username}');
request.setHeader('Authorization', 'Basic ' + EncodingUtil.base64Encode(authHeaderValue));

...nor this:

Blob authHeaderValue = 
request.setHeader('Authorization', 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf('{!$Credential.Username}')));
Related Topic