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:
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]