+ Start a Discussion
Rajesh ShahRajesh Shah 

Login as another User in Apex Class

In our S-Control, due a particular reason, we first login using another User.
The following is the code to do so
var usrPwd = null;
  var usrName = null;
  var currentUrl = sforce.connection.serverUrl;
  var results = sforce.connection.query("Select Password__c,Username__c from Administrator__c");
  records = results.getArray("records");
  if (records.length > 0)
   admName = records[0].get("Username__c");
   admPwd = records[0].get("Password__c");
    sforce.connection = new sforce.Connection();
   var loginResult = sforce.connection.login(usrName, usrPwd);
  catch (error)
   alert("Failed to Authenticate Administrator, + error);
  sforce.connection.serverUrl = currentUrl;
Now I need to migrate the same code to an Apex Class. I can query in an Apex Class but can I login as another User in apex Class in the same way as I am currently doing in S-Control code.
Best Answer chosen by Admin (Salesforce Developers) 
Since Apex code runs as System Admin, I am not sure you will need to login as another user. Are you logging in as another user to apply the proper sharing rules and data visibility? If so, you will want to use the "with sharing" keyword when defining the apex class that applies your logic. You can find the online documentation here:

I hope that helps.