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.
I don’t think an attribute is the best way to implement a feature like this. For the most part attributes merely act as meta-data on types and members (Aspect Oriented stuff aside). You’d need to write something to check for that attribute, and re-route the method call accordingly. If you already have some AOP code in place this shouldn’t be much of a chore, but if you don’t you’d likely be much better served by something like this:
And then call it like this:
This allows you to centralize the impersonation code without having to mess around with reflection, codeweaving, etc.