How to Retrieve Named Principal Values in Apex?

Spread the love

Question

I have a scenario where I need to generate an additional token before making a callout. This token requires API_KEY and API_SECRET, which I have stored in Named Principals.

The usual approach, as mentioned in Salesforce documentation and forums, is to use the following formula:

String API_KEY = '{!$Credential.MyTest_ExtCredentials.API_KEY}';

However, this does not work because the formula is only resolved when used as a header value at the exact moment the call is made. I need to retrieve these values before the request is sent.

Is there a way to get the values from Named Principal as a string in Apex?

Answer

Salesforce does not allow direct retrieval of Named Principal values as a string in Apex. This restriction is in place for security reasons, ensuring that sensitive credentials are not exposed within Apex code. Named Credentials, including Named Principals, are designed to be used only at runtime when making a callout, and their values cannot be accessed directly.

Why Can’t We Retrieve Named Principal Values Directly?

Named Credentials resolve dynamically only at the time of the HTTP request. When you try to store a Named Principal value in a variable, the formula {!$Credential.MyTest_ExtCredentials.API_KEY} remains unresolved because Salesforce does not allow direct access to these values within Apex.

Alternative Approaches

1. Using a Named Credential in the Callout Directly (Recommended)

Rather than trying to extract the API Key and Secret beforehand, the best approach is to let Salesforce handle authentication using Named Credentials. You can reference a Named Credential directly in an Apex HTTP request like this:

HttpRequest req = new HttpRequest();
req.setEndpoint('callout:MyNamedPrincipal/someEndpoint');
req.setMethod('GET');

Http http = new Http();
HttpResponse res = http.send(req);

In this case, Salesforce automatically injects the required credentials when making the request.

2. Storing API Keys Securely in a Protected Custom Setting

If you absolutely need access to the API Key and Secret before making a request, consider storing them in a protected Custom Setting or Custom Metadata. However, storing secrets in plaintext is not recommended, so you should encrypt them manually using the Crypto class:
Storing an Encrypted API Key

String encryptedApiKey = EncodingUtil.base64Encode(Crypto.encryptWithManagedIV('AES256', Blob.valueOf('Your_API_KEY_Here')));

Retrieving and Decrypting the API Key

Blob decryptedBlob = Crypto.decryptWithManagedIV('AES256', EncodingUtil.base64Decode(encryptedApiKey));
String decryptedApiKey = decryptedBlob.toString();

This method ensures that your API keys remain secure while allowing Apex to retrieve them when needed.

3. Pre-Fetching Tokens via an External Authentication Provider

If your integration requires a token before making a call, consider using an OAuth 2.0 provider that pre-fetches tokens for you. This way, your Apex code can retrieve the token from the external system before making the request.

HttpRequest req = new HttpRequest();
req.setEndpoint('https://external-auth-provider.com/oauth/token');
req.setMethod('POST');
req.setBody('grant_type=client_credentials&client_id=your_client_id&client_secret=your_client_secret');

Http http = new Http();
HttpResponse res = http.send(req);
String accessToken = res.getBody(); // Store this token for future use

Then, you can use this pre-fetched token in your actual request.

In Summary, Salesforce does not allow direct retrieval of Named Principal values as a string in Apex. Instead, you should use Named Credentials as intended, letting Salesforce handle authentication dynamically during callouts. If you need to access API keys before making a request, the most secure approach is to store them in a protected Custom Setting with encryption or use an external authentication provider.

Enroll for Career-Building Salesforce Training with 100% Money Back Guarantee

Our Salesforce Course is designed to offer a thorough understanding of the Salesforce platform, equipping you with the essential skills to excel in the CRM industry. The program includes important modules like Salesforce Admin, Developer, and AI, seamlessly combining theoretical knowledge with practical application. By working on real-world projects and assignments, you will develop the expertise to confidently address complex business challenges using Salesforce solutions. Our expert instructors ensure you gain both technical competence and industry-relevant insights to succeed within the Salesforce ecosystem.

Along with technical expertise, our Salesforce training in Pune provides personalized mentoring, certification guidance, and interview preparation to help boost your career. You’ll have access to comprehensive study materials, hands-on project experience, and one-on-one support throughout your journey. By the end of the course, you’ll be prepared for certification exams and equipped with the practical problem-solving skills that employers value. Start your Salesforce career with us and explore a world of exciting opportunities. Enroll for a Free Demo now!

Open Chat
1
Dear Sir/Madam
How can I help you?