5

Is there a way of accessing the data (exact fields) stored in Spring 15' Named Credentials from apex? For example the username, password and endpoint link fields? And I don't mean for the callout, but for other purposes.

6

You can use Named Credentials to create an End point URL with necessary parameters. For example, if this is is your URL:

https://www.someendpointurl.com?param1=named&param2=credentials

In Apex, You can access this URL like this:

request.setEndpoint('callout:EndPointURL');

Where, EndPointURL is the Name of the Named Credentials.

Benefits of using Named Credentials:

  • Authentication is done by Salesforce and you need not to worry about that.
  • No need to create a Remote Site Setting if using a Named Credential.
  • Callout is easier to maintain. No hard coding involved.
  • If are also using Sandboxes for callout, just create the Named Credentials with the same name and save different URL.

Hope this helps..!!

But actually accessing the data stored in the Named Credentials fields (e.g. as String) is not possible.

8
  • Thanks, I've read this and it was precisely the reason why I wanted to use it. But I also need to access the fields stored in the object. For other purposes than callouts. – JaKu Jun 16 '15 at 9:02
  • @JaKu - So, you want to access other fields of Named Credentials? – the_phantom Jun 16 '15 at 15:12
  • I wouldn't call them 'other' fields. I would like to access the values in the fields that are stored there. I don't think it is possible. I think that the use of the object is write-use, not write-read-use. – JaKu Jun 17 '15 at 6:32
  • Yes, that's not possible. – the_phantom Jun 17 '15 at 16:52
  • 1
    @Monish Well, you should always pass username, password or token in the Authorization http header key. Passing credentials as url parameter is not safe. – the_phantom Nov 12 '18 at 14:01
2

One option is to use Merge Fields for Apex Callouts That Use Named Credentials. This won't explicitly give you access to the data from the named credential in Apex, but it will allow you to alter how it is used in any callout.

For example, you could define custom request headers:

// non-standard authentication
req.setHeader('X-Username', '{!$Credential.UserName}');
req.setHeader('X-Password', '{!$Credential.Password}');

Or you could include the credentials in the request body:

req.setBody('UserName:{!HTMLENCODE($Credential.Username)}')
req.setBody('Password:{!HTMLENCODE($Credential.Password)}')

Note that there is a special case in a request body where you can use the HTMLENCODE formula function to escape special characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.