[SalesForce] UserName and Password in Request body of apex callout using Named Credentials

I am able to make an apex callout by passing the username and password in the request body.

String endpoint='https://xyz...com/';
String userID='xyz';
String password='pass';
String jsonBody ='userID=' + userID + '&password=' + password;
HTTP auth = new HTTP();
HTTPRequest r = new HTTPRequest();
r.setClientCertificateName('certificate_Name');
r.setEndpoint(endpoint);
r.setMethod('POST');   
r.setBody(jsonBody);
r.setHeader('Content-Type','application/x-www-form-urlencoded');
HTTPResponse authresp=new HttpResponse();
authresp = auth.send(r); 
system.debug(authresp);

I have a requirement to use the above same approach of passing the credential in request body but I have to do it using Named Credentials.

I did go through the link – https://developer.salesforce.com/docs/atlas.en-us.198.0.apexcode.meta/apexcode/apex_callouts_named_credentials_custom_headers_bodies.htm to learn that –

The Salesforce admin must set up the named credential to allow Apex
code to construct headers or use merge fields in HTTP headers or
bodies.

I am trying some approach to include the named credentials in the above code but I am do not get a success result so far. Below is what I tried:

Named Credential:

enter image description here

Code using Named Credential:

    HTTP auth = new HTTP();
    HTTPRequest r = new HTTPRequest();
    r.setEndpoint('callout:Named_CREDENTIAL');
    String jsonBody ='userID=' + '{!$Credential.Username}' + '&password=' + '{!$Credential.Password}';
r.setBody(jsonBody);
    r.setMethod('POST');   
    r.setHeader('Content-Type','application/x-www-form-urlencoded');
    HTTPResponse authresp=new HttpResponse();
    authresp = auth.send(r); 
    system.debug(authresp);

Response I got – System.HttpResponse[Status=Forbidden, StatusCode=403]

Best Answer

When using merge fields you need to actually set the body like

string bdy = '{ "username" : "{!$Credential.Username}", "password" : "{!$Credential.Pasword}"}'

req.setBody(bdy);

The format will depend on the requirements of the external system

The Release Notes May be helpful a would the Documentation

Related Topic