Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is it possible to use system.runAs() methods in a trigger? If it possible please provide sample code.

share|improve this question
2  
no not possible. system.RunAs() methods only available in test class. – Ratan Jan 11 at 16:42
    
Perhaps you can invoke a utility class and use the with sharing keyword to enforce the user sharing rules if that is your use case. – Antonio Manente Jan 11 at 16:45
2  
What is your use case for this? – Brian Mansfield Jan 11 at 16:49
    
Is this still an open question? – Adrian Larson Mar 7 at 15:06

This method can only be used in tests. You can find the documentation for System.runAs here. Its documentation says:

All of the specified user's record sharing is enforced during the execution of runAs. You can only use runAs in a test method. For more information, see Using the runAs Method.

share|improve this answer

Short answer: no.

Longer answer: The System.runAs block was designed to support unit testing, and as such, is only allowed in a unit test context. If you're trying to impersonate another user, you would have to somehow "log in" as them and perform whatever you're doing by way of an API call. This, in turn, suggests you'd need to, at minimum, use a @future, Queueable, Schedulable, or Batchable method/class, call the API to log in as that user (I'd suggest REST here, but any of the APIs that provide a login method would be suitable), then perform whatever it is you're trying to do using that newly created session ID. This entire process is fairly trivial, but completely not obvious, and would take some initial investment in research to get it right.

share|improve this answer
    
This is a good outline of the technical implementation, but seems to carry huge risk. I'm curious what kind of steps you might take to mitigate that? – Adrian Larson Jan 11 at 17:17
    
@AdrianLarson Personally, I'd use OAuth2-- make the user to be impersonated login and store their refresh token and auth token in a custom setting, encrypted, of course. This way the user being impersonated could terminate the session at any time, and their username nor password is ever exposed directly. Admins would still be able to recover the data, but normal users wouldn't know how to get at the data (or even have the permissions needed to write the necessary code). – sfdcfox Jan 11 at 17:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.