Newer Version Available

This content describes an older version of this product. View Latest

Merge Fields for Apex Callouts That Use Named Credentials

To construct the HTTP headers and request bodies of callouts to endpoints that are specified as named credentials, use these merge fields in your Apex code.
Merge Field Description
{!$Credential.Username}

{!$Credential.Password}

Username and password of the running user. Available only if the named credential uses password authentication.
1// non-standard authentication
2req.setHeader('X-Username', '{!$Credential.UserName}');
3req.setHeader('X-Password', '{!$Credential.Password}');
{!$Credential.OAuthToken} OAuth token of the running user. Available only if the named credential uses OAuth authentication.
1// The external system expects “OAuth” as 
2// the prefix for the access token.
3req.setHeader('Authorization', 'OAuth {!$Credential.OAuthToken}');
{!$Credential.AuthorizationMethod} Valid values depend on the authentication protocol of the named credential.
  • Basic—password authentication
  • Bearer—OAuth 2.0
  • null—no authentication
{!$Credential.AuthorizationHeaderValue} Valid values depend on the authentication protocol of the named credential.
  • Base-64 encoded username and password—password authentication
  • OAuth token—OAuth 2.0
  • null—no authentication
{!$Credential.OAuthConsumerKey} Consumer key. Available only if the named credential uses OAuth authentication.
  • When you use these merge fields in HTTP request bodies of callouts, you can apply the HTMLENCODE formula function to escape special characters. Other formula functions aren't supported, and HTMLENCODE can’t be used on merge fields in HTTP headers. The following example escapes special characters that are in the credentials.
    1req.setBody('UserName:{!HTMLENCODE($Credential.Username)}')
    2req.setBody('Password:{!HTMLENCODE($Credential.Password)}')
  • When you use these merge fields in SOAP API calls, OAuth access tokens aren’t refreshed.

Note