Can you change the running user in your APEX logic, not just test coverage? The documentation only details out doing System.runAs() for testing purposes.


2 Answers 2


There are two approaches I have seen work in the past to approximate impersonation via Apex. Each approach takes a nontrivial amount of setup to support a impersonating a given user, so if you want to be able to impersonate any user on demand, the answer is pretty much no.

  1. Scheduled Apex
    The user who schedules the job is the context user for the operation. It only allows you to run code at predefined intervals, but is low effort and a fairly standard usage of the platform.

  2. OAuth
    This approach is a bit of a hack, but you can use callouts to obtain a session for a different user. Once you have that, you would be able to make further callouts using that session token, and each such transaction would run as that user. It allows you to impersonate on demand, but should be used with caution. If you go down this route, probably the safest path is to use a Named Credential to store a given user's password, and authenticate every time you wish to impersonate.


No. System.runAs() is only supported in test context.

Platform Event Triggers fire in the context of a user ("Automated Process") other than the running user for the process that originally published the event. Otherwise, the running user context is preserved across all sequences of programmatic functionality, including asynchronous Apex.

  • darn. Yea I am trying to change the running user from a Platform Event
    – Olivia
    Commented Mar 13, 2018 at 20:32
  • Actually... you can authenticate as someone else via callout. I think...can't remember the exact mechanics of it.
    – Adrian Larson
    Commented Mar 13, 2018 at 20:58
  • @AdrianLarson You can, but you have to already have a way to access the user (e.g. a known password or valid session Id).
    – sfdcfox
    Commented Mar 13, 2018 at 21:04
  • @sfdcfox Yeah or a Named Credential. Someone had it set up in a previous org using plaintext passwords and a List Custom Setting. Yuck.
    – Adrian Larson
    Commented Mar 13, 2018 at 21:07
  • I remember @Olivia's neck-deep call sequence from a previous question. Olivia, please don't try to change the running user with a callout! :)
    – David Reed
    Commented Mar 13, 2018 at 23:24

You must log in to answer this question.

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