I have some methods that need to run as a certain service account, so I do the normal thing:
public DoSomeWorkAsServiceAccount() {
...
// assume I am given tokenHandle
WindowsIdentity newId = new WindowsIdentity(tokenHandle);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
...
// do the work here
...
impersonatedUser.Undo();
}
I'd like to avoid writing this code in every method, so I was thinking of creating a custom attribute:
[Impersonate(tokenHandle)]
public DoSomeWorkAsServiceAccount() {
// do the work
}
So here are my questions:
- Is this possible?
- Can you show me something that will avoid code duplication?
Thanks in advance.