[SalesForce] Running a Batchable under a different User than the User that called Database.executeBatch

To avoid exceeding the flex queue limit, we would like to chain a batchable, but change the User that the batchable runs under for each new batchable so that its updates are tied to the correct User i.e. so the "Last Modified By" is correct.

In 2014 there was no way to do this – see Can you run a Batchable Apex bulk update as a different user? – and AFAIK there is still now way to do this. Is there?

Best Answer

What you probably want is to Give the Administrator the ability to make "ghost" updates, but we've been waiting a decade for that idea. Technically, with Named Credentials, you could impersonate a user in an API call, but they'd have to basically give you their username and password.

If you were really serious about it, and it had to be done, you could write a Connected App, have the user grant access (with Offline Access) to that Connected App, capture the Refresh Token, then you can do all sorts of things with that Refresh Token using API calls, such as an Execute Anonymous script to kick off the additional queueable calls, etc.

Note that this method is a Bad Idea. In fact, it's a Very Bad Idea. Anyone who figures out how to get to the Refresh Tokens could impersonate any user in your system. You'd have to take special care to keep the data encrypted and not leak it in debug logs, etc. All of that work just to let someone impersonate someone else isn't something I'd consider lightly.

For now, you'll probably just want to accept that the Last Modified audit fields will show what they're intended to show. You might want to raise awareness for the Idea mentioned in the first paragraph.