Monday, April 19, 2010

How to run code in the security context of another user

If you are reading this, you're probably an Ax administrator in your company. Or you have full control over your Ax system.
But that's not the case with all the users in your Ax environment (thank God for that).
Security limits normal users in their actions, sometimes so much they cannot get the job done. Sometimes exceptions are needed, in order to let a "normal" user perform some actions. Or vice versa, as an administrator you want to run code with "lower" security rights for testing. Or you need different security rights when running batch operations.

Ax is equiped with a function to allow code to run as if it's run by another user, it's called RunAs. (We're not talking about the RunAs from Windows, which allows you to run complete programs with different security rights.)

We are running Ax with our normal user account, only temporary impersonating another user's security.

Primary condition: The code is started on the server.
Seconday condition: The called function is a static one.

Take following method of a class we have created as example.

server static void MyMethod(UserId _UserId)
   RunAsPermission perm;
   perm = new RunAsPermission(_UserId);

   RunAs(_UserId, classnum(YourClassName), "YourMethodName");


Now we can call that piece of code from for example a job, like this:


That's all there is to it. By calling MyMethod, the runAs is activated and the defined class and method are activated with different rights.

If necessary, you can pass on additional parameters with the call to RunAs. You can include a container in your arguments. Like this:

RunAs(_UserId, classnum(YourClassName), "YourMethodName", [param1,param2]);
Be careful with what you program, as you can give any normal user administrator rights like this. Sometimes convenient if a user doesn't have specific table access, but sometimes simply dangerous or unwanted.

No comments:

Post a Comment