Although Named Credentials cannot be used to manage this authentication flow, it can be used to obtain the token without needing to utilise Custom Settings to store the username and password.
Create a Named Credential that will only be used to obtain the token.
Property |
Value |
Notes |
Label |
|
Naming intends to specify that this is only for the token. |
URL |
https://SERVICE_URL/token |
Again, very specific to just the token call. |
Identity Type |
Named Principal |
This particular example uses the same username/password for all users. |
Authentication Protocol |
|
|
Username |
USERNAME |
The username required for the token request. |
Password |
PASSWORD |
The password required for the token request. |
Generate Authorization Header |
false |
If enabled, Salesforce will generate an authorization header, but the external service does not want it. The external service expects the username and password as separate properties in JSON. |
Allow Merge Fields in HTTP Body |
true |
Enabling this will allow usage of the username & password fields in apex. |
Anonymous Apex
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:SERVICE_Token_Request');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody('{"Username":"{!HTMLENCODE($Credential.Username)}",' +
'"Password":"{!HTMLENCODE($Credential.Password)}"}');
Http http = new Http();
HTTPResponse res = http.send(req);
Map<String, Object> response = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
String securityToken = (String)response.get('securityToken');
System.debug(securityToken); // TOKEN
Hope this helps!
Join the Salesforce admin course to learn more!