Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a attribute to make .net impersonate another user?

I am familiar with impersonating an account in .net by using:

dim myIdentity as WindowsIdentity = someIdentity  
using ctx as WindowsImpersonationContext = myIdentity.Impersonate()  
    doStuff()  
end using

Is it possible to define a .net attribute so that I could write something like:

< runAsUser(someIdentity) > public sub doStuff()

and then have the .net framework always impersonate when running the method doStuff()?

Update Okay, I'm told that this may be impossible because arguments to an attribute constructor must be constants which would rule out passing in the user's identity.

Let me ask the question a little bit differently: Suppose there were a function getUserWindowsIdentity() that returns an identity associated with the logged in user.

Could I then use < runAsLoggedInUser) > public sub doStuff() > to make the framework always impersonate the user id returned by getUserWindowsIdentity when running the doStuff() method?

like image 314
Vivian River Avatar asked Dec 14 '25 09:12

Vivian River


2 Answers

No, such magic does not exist in the .NET framework. You'd have to write the code yourself, using Reflection to read the attribute. That code will look a lot like the code you already have, just slower and with the code to read the attribute added.

like image 70
Hans Passant Avatar answered Dec 16 '25 22:12

Hans Passant


I'm fairly certain this can't be done. You might be able to simulate it with PostSharp (or similar.)

Parameters passed to Attribute constructors must be constants, meaning they can't be reference types at all. I would question the use case where a code block should always run under the same hard-coded credentials, as well.

like image 42
Toby Avatar answered Dec 16 '25 22:12

Toby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!