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.
2 Answers
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¶m2=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.
-
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.– JaKuJun 16, 2015 at 9:02
-
@JaKu - So, you want to access other fields of Named Credentials? Jun 16, 2015 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.– JaKuJun 17, 2015 at 6:32
-
-
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. Nov 12, 2018 at 14:01
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.
-
the
$Credential
merge fields return the username and password of the current running user. If I want to store username and password in a named credential and use them in non-standard authorization headers for my HTTP request, this doesn't work– Vid LDec 23, 2021 at 14:42