HOWTO: Impersonate Another User to Execute Code in X++
!
Warning: This post is over 365 days old. The information may be out of date.Although this is not common and goes against a few Best Practices, in very specific scenarios we may need to execute a X++ fragment (a method call) in the context of a user different from the one running the current session, either from a client session or a Batch process. To execute a method call under a specific user, we use this code:
// ...
// User that will execute the method
UserId postingUserId = parms.PostingUserId != '' ? parms.PostingUserId : curUserId();
new RunAsPermission(postingUserId).assert();
// Call to: MyClass.myClassMethod(methodParm1, methodParm2)
// BP Deviation Documented
runAs(postingUserId, classNum(MyClass), 'myClassMethod', [methodParm1, methodParm2]);
CodeAccessPermission::revertAssert();
// ...
I insist this is not common and, as always when doing this kind of thing, it introduces some security risks. Still, I leave the code here so I can find it next time I need it ;)