I was wondering if updating an authentication parameter of an External Credential was possible from an Apex method.

The main goal of this function would be to programmatically store an access token which is according to Salesforce the best practice but I can't find a way to change the External Credential / Named Credential from an Apex code.

Thank you.

  • 1
    Sounds like a XY Problem. Please edit your question and explain your goals.
    – identigral
    Sep 19, 2023 at 16:01
  • Hi @identigral thank you for your comment. This is not an XY Problem as my X problem is to look for the most suitable place to store an access token and according to sfdcfox's response on (Where to Store Token Auth?)[salesforce.stackexchange.com/questions/149921/… , the best place would be a named credential / external credential. Here my problem would be how to set this credential from an Apex code.
    – Diaboloxx
    Sep 20, 2023 at 9:42

1 Answer 1


Yes, it is possible using the ConnectApi.NamedCredentials.patchCredential() method. You can find the documentation of the method here.

As an example, this code updates a External Named credential called ExternalCred with:

  • Custom authentication protocol
  • A single principal called Authentication
  • One encrypted autentication parameter inside the principal called Secret
ConnectApi.CredentialInput newCredentials = new ConnectApi.CredentialInput();
newCredentials.authenticationProtocol = ConnectApi.CredentialAuthenticationProtocol.Custom;

Map<String, ConnectApi.CredentialValueInput> creds = new Map<String, ConnectApi.CredentialValueInput>();
ConnectApi.CredentialValueInput secret = new ConnectApi.CredentialValueInput();
clientIdValue.encrypted = true;
clientIdValue.value = secretValue;
creds.put('secret', secret);

newCredentials.credentials = creds;
newCredentials.externalCredential = 'ExternalCred'
newCredentials.principalType = ConnectApi.CredentialPrincipalType.NamedPrincipal;
newCredentials.principalName = 'Authentication';

You will need to tweak it depending on the authorization type and your special needs.

  • Hi Alberto! I was trying to implement this but received an error on the clientValue lines. Can you clarify this? Apr 11 at 18:12
  • Can you provide more information about the error you are getting and the code you are writing?
    – Alberto
    Apr 12 at 8:36
  • I replaced Lines 6 & 7 with secret.encrypted = true; secret.value = 'value'; And received the error The externalCredential parameter value doesn't exist or you may not have permission to access it What I am trying to do is update the existing Parameter, refresh_token in an existing External Credential Apr 12 at 12:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .