Use case

During sandbox creation or refresh (Enterprise, not ISV use case), with Apex class implementing SandboxPostCopy, invoke MetadataAPI to delete stuff that shouldn't be in the sandbox (like Production Named Credentials)

While Apex can make callouts to the same org including the Metadata API, one needs a sessionId.


  • Sandbox creation/refresh execute as Automated Process user
  • UserInfo.getSessionId() as of Winter 19 returns a valid sessionId in async scenarios but not if the running user is Automated Process
  • Publishing a Platform Event and consuming with a Trigger to do the callout won't work because Platform Event subscribers are Automated Process user. Same issue if I launched a scheduled class.
  • Org is not using MyDomain (yet)
  • Any Remote Site Settings inherited by the sandbox from PROD will point at PROD

I can't quite get my head around something to configure in PROD that gets copied into the sandbox during sandbox creation and that Apex would have access to and thus be able to do a callout to the same org without a sessionId that would

  • point at this sandbox
  • be secure
  • I tried getting this going using a JWT Auth flow to authenticate a user for the Session ID. Unfortunately couldn't get it to authenticate without having the Consumer Key of the Connected App in the sandbox. Ended up needing to go with the Visualforce page to get this going. Would love to find a secure way to get a Session ID!
    – Clint
    Jul 8, 2019 at 13:51
  • Can you give me a sample snippet of apex class to use metadata api to turn off trigger validation rule?
    – Sudarshan
    Nov 2, 2019 at 2:58
  • @Sudarshan as I stated above, there's no sessionId available to make a call to MDAPI si code won't help.
    – cropredy
    Nov 2, 2019 at 4:31
  • @cropredy Thank you for your response.
    – Sudarshan
    Nov 3, 2019 at 16:27
  • 1
    Re: callouts. There's a KI currently preventing callouts: issues.salesforce.com/issue/a028c00000gAwhXAAS/…
    – identigral
    Dec 1, 2023 at 19:35

1 Answer 1


There's no way you're going to get this working with SandboxPostCopy. Instead, you'd want to write a batch/shell script, or a Visualforce page that an administrator would need to run once the new org is up and running. This would be the only foolproof way to get everything done that needs to be done.

  • 1
    Well this is disappointing. I was looking for a way more likely to happen automatically. Having an admin do this via a script/VF page is my fallback.
    – cropredy
    May 17, 2019 at 4:19
  • @cropredy Yeah, you know how much I hate saying "no," but given all the restrictions with SandboxPostCopy, there really isn't an ideal solution here.
    – sfdcfox
    May 17, 2019 at 4:38

You must log in to answer this question.

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