+ Start a Discussion
Conor DowneyConor Downey 

Run apex code under another user

Is it possible to run Apex code under a different user than the logged in one?

So someone has logged in and they kick off some Apex code, but I need that specific method to run under an admin user? Is that possible?

Thanks.
PavanKPavanK
User RunAs() method

In test class create user with test profile
user objUser = new user(name='', profileid='', etc);
insert objUser;

Then use
system.RunAs(objUser)
{
//test logic here
}

Please mark this answer as best if it helped you.
UC InnovationUC Innovation
I believe the System.runAs() method can only be used in test methods.  If you want to run the method as admin, then you can use the 'without sharing' keyword on the class:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_keywords_sharing.htm

Hope that helps!
Cloud_forceCloud_force
system.runas(), which we generally use during test classes cannot be used during main execution.

It will always run as the logged in user or system mode. If you have specific user with which you want to run the code then there's 1 way i can think of but that will be the last one you would want to follow and also that will need the credentials of the user with which you want to run the code.

Login through that user using rest api and run the method. http://www.cloudforce4u.com/2015/10/rest-api-integration-salesforce-apex.html
 
Sumanta SatpathySumanta Satpathy
The system method runAs enables you to write test methods that change the user context to an existing user or a new user so that the user’s record sharing is enforced. The runAs method doesn’t enforce user permissions or field-level permissions, only record sharing.
Chuck RamseyChuck Ramsey
From the Apex Developer Guide (API V44.0) section entitled  Using the runAs (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_tools_runas.htm)() Method:

You can use runAs only in test methods.

I have not found any exception to this rule, nor any workaround.