You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add asynchronous overload of WindowsIdentity.RunImpersonated #24009
ASP.NET Core is getting many requests for users that want to impersonate the authenticated user of the request and perform actions on their behalf. The main problem is that many of these actions are asynchronous, such as database access, but RunImpersonated is synchronous. Users have repeatedly made the mistake of starting an asynchronous operation within RunImpersonated and then returning the Task. Exiting RunImpersonated revokes the impersonation and can cause errors or reverting to the base identity in the Task.
Proposal: public static Task RunImpersonatedAsync(SafeAccessTokenHandle safeAccessTokenHandle, Func<Task> func) public static Task<T> RunImpersonatedAsync<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<Task<T>> func)
Note that ExecutionContext in .NET Core does not flow impersonation. The requested functionality could hopefully be achieved with an AsyncLocal and a valueChangedHandler that took care of impersonating and reverting the impersonation, but it would need to be prototyped.
cc: @kouvel
@Tratcher in other runtimes, we set the thread identity and ran the entire call graph under that identity. Then when exiting that call, we reverted the threads identity.
Don't know if that model works in core.
@Tratcher within a process (or appdomain) the new thread has the identity associated with the thread that spawned it. Cross thread or appdomain requires serializing. Cross process shouldn't be used because the NTTOKEN is just a handle and the values are only unique within a process. A windowsIdentity hydrated could point a different user. Very unlikely as the handle would have to be a handle to an nttoken.
ExecutionContext in dotnet core does seem to flow Impersonation (#25627). ExecutionContext also does not have an explicit lifetime, while token handle's do.
Instead of adding a RunImpersonatedAsync method, I'd like to propose an alternative api;
public IDisposable BeginImpersonation(SafeAccessTokenHandle token)
Which would internally still use an AsyncLocal & ExecutionContext to flow the impersonation across async continuations. While also ensuring that the impersonation cannot outlive the lifetime of the returned IDisposable.
Explicitly documenting that any task that escapes the lifetime of the disposable will still execute, but no longer be impersonating that user.
NetFx had Impersonate() and would flow the impersonated identity across async operations via the ExecutionContext (?). CoreFx doesn't have this API or implicit flow.
NetFx had Impersonate() and would flow the impersonated identity across async operations via the ExecutionContext (?). CoreFx doesn't have this API or implicit flow.
As @lakeman said, it seems CoreFX is flowing the impersonation. RunImpersonated creates an ExecutionContext and sets that AsyncLocal s_currentImpersonatedToken from within. It then uses the AsyncLocal ThreadContextChanged event to maintain the correct impersonation on the threads the task runs on.
What would an async verions of RunImpersonatedInternal do differently? It could potentially await the Action, but currently nothing happens after the action is called.
Instead of adding a RunImpersonatedAsync method, I'd like to propose an alternative api;
Wouldn't BeginImpersonation essentially just be Impersonate from NetFX? Why wasn't it brought over?
Perhaps @Tratcher's suggestion will provide more implementation flexibility for corefx devs in the future to manage the SafeAccessToken lifetime more appropriately without holding it in an AsyncLocal.
Below is a quick program to demonstrate the impersonation 'flowing' on Tasks returned from RunImpersonated:
FYI, users of my SimpleImpersonation library are also encountering this, as I use WindowsIdentity.RunImpersonated internally (paired with a P/Invoke to LogonUser for the value add, similar to the above code). A recommended workaround would be useful, especially if I could apply it without changing my public API. Thanks.
Can we get the docs updated? I consider the above kind of the gold standard that I share, and you wrote it, so thanks for getting the ball rolling on that stuff. I agree about the usage aspect. Any API that requires you to use it one way and one way only is doomed to fail. It's not dissimilar to the issues you found with HttpContextAccessor. It's better than it was with HttpContext.Current, but still has issues.
@davidfowl, can you elaborate on the pit-of-failure-ness? If there were a public static Task<T> RunImpersonatedAsync<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<Task<T>> func), it would behave exactly the same way. I get the concern that the current signature is non-obvious, but is that the concern you're referring to, or something else?
what are the chances of this change making it into the full framework?
What change? New overloads? Close to zero. But as noted, these overloads are also completely implementable as literal one-liners on top of the existing API surface area:
These APIs can be simply implemented over the existing one, thanks for generics.
However, it's not obvious that is in fact supported. Adding explicit overload that are named with the Async suffix would make sense
We considered adding a cancellation token, but given callers likely have to allocate a closure anyway, this doesn't save anything and impersonation is already expensive.
@stephentoub, I am still trying to get a clear answer whether this works on full framework. Related issue has been sitting there for a while, and documentation has not been updated, either.
Activity
stephentoub commentedon Oct 31, 2017
Note that ExecutionContext in .NET Core does not flow impersonation. The requested functionality could hopefully be achieved with an AsyncLocal and a valueChangedHandler that took care of impersonating and reverting the impersonation, but it would need to be prototyped.
cc: @kouvel
madrianr commentedon Nov 1, 2017
Is it true that we cannot expect such a feature in a short period of time?
can you give us a timeframe?
robert
brentschmaltz commentedon Nov 1, 2017
@Tratcher @stephentoub @madrianr are we discussing Integrated Windows Auth (IWA) ?
Tratcher commentedon Nov 1, 2017
Primarily Kerberos for the delegation capabilities.
brentschmaltz commentedon Nov 1, 2017
@Tratcher in other runtimes, we set the thread identity and ran the entire call graph under that identity. Then when exiting that call, we reverted the threads identity.
Don't know if that model works in core.
Tratcher commentedon Nov 1, 2017
How did that flow to the async actions?
brentschmaltz commentedon Nov 1, 2017
@Tratcher within a process (or appdomain) the new thread has the identity associated with the thread that spawned it. Cross thread or appdomain requires serializing. Cross process shouldn't be used because the NTTOKEN is just a handle and the values are only unique within a process. A windowsIdentity hydrated could point a different user. Very unlikely as the handle would have to be a handle to an nttoken.
Tratcher commentedon Nov 1, 2017
And threadpool threads? That's where most of this code runs.
lakeman commentedon Dec 1, 2017
ExecutionContext in dotnet core does seem to flow Impersonation (#25627). ExecutionContext also does not have an explicit lifetime, while token handle's do.
Instead of adding a RunImpersonatedAsync method, I'd like to propose an alternative api;
Which would internally still use an AsyncLocal & ExecutionContext to flow the impersonation across async continuations. While also ensuring that the impersonation cannot outlive the lifetime of the returned IDisposable.
Explicitly documenting that any task that escapes the lifetime of the disposable will still execute, but no longer be impersonating that user.
stephentoub commentedon Dec 1, 2017
It doesn't, at least not explicitly, i.e. there's no SecurityContext stored on the ExecutionContext as there is in netfx. But (and I didn't realize this was already done, hence my earlier comment), it appears it's trying to simulate it using AsyncLocal, similar to what I suggested earlier:
https://github.com/dotnet/corefx/blob/9a2e5d8f0e7f816f983bce75f5bba22811df4994/src/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs#L640
bartonjs commentedon Jan 10, 2018
Is this a "this works on NetFx but is broken on CoreFx", or a "now that async is so easy we see a feature hole"?
Tratcher commentedon Jan 10, 2018
NetFx had
Impersonate()and would flow the impersonated identity across async operations via the ExecutionContext (?). CoreFx doesn't have this API or implicit flow.Tratcher commentedon Jun 6, 2018
ping people keep doing this wrong and are set up for failure.
https://github.com/lilpug/ASP.NET-Core-Impersonation/blob/96917b51c578aa7d18c9636a4a58f4571822890f/lib/middleware/pipeline.cs#L46-L49
wpbrown commentedon Sep 10, 2018
As @lakeman said, it seems CoreFX is flowing the impersonation. RunImpersonated creates an ExecutionContext and sets that AsyncLocal s_currentImpersonatedToken from within. It then uses the AsyncLocal ThreadContextChanged event to maintain the correct impersonation on the threads the task runs on.
What would an async verions of
RunImpersonatedInternaldo differently? It could potentially await the Action, but currently nothing happens after the action is called.Wouldn't BeginImpersonation essentially just be Impersonate from NetFX? Why wasn't it brought over?
Perhaps @Tratcher's suggestion will provide more implementation flexibility for corefx devs in the future to manage the SafeAccessToken lifetime more appropriately without holding it in an AsyncLocal.
Below is a quick program to demonstrate the impersonation 'flowing' on Tasks returned from
RunImpersonated:Program Output
mattjohnsonpint commentedon Sep 13, 2018
FYI, users of my SimpleImpersonation library are also encountering this, as I use
WindowsIdentity.RunImpersonatedinternally (paired with a P/Invoke toLogonUserfor the value add, similar to the above code). A recommended workaround would be useful, especially if I could apply it without changing my public API. Thanks.43 remaining items
davidfowl commentedon Oct 21, 2019
Yes and honestly there were bugs that prevented it from working like this in the early days. The API is still a pit of failure IMO.
Macromullet commentedon Oct 21, 2019
Can we get the docs updated? I consider the above kind of the gold standard that I share, and you wrote it, so thanks for getting the ball rolling on that stuff. I agree about the usage aspect. Any API that requires you to use it one way and one way only is doomed to fail. It's not dissimilar to the issues you found with HttpContextAccessor. It's better than it was with HttpContext.Current, but still has issues.
stephentoub commentedon Oct 21, 2019
@davidfowl, can you elaborate on the pit-of-failure-ness? If there were a
public static Task<T> RunImpersonatedAsync<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<Task<T>> func), it would behave exactly the same way. I get the concern that the current signature is non-obvious, but is that the concern you're referring to, or something else?davidfowl commentedon Oct 21, 2019
That's the main concern. I think adding the following methods(s) would suffice:
avivanoff commentedon Oct 23, 2019
@stephentoub, @davidfowl, what are the chances of this change making it into the full framework?
stephentoub commentedon Oct 23, 2019
What change? New overloads? Close to zero. But as noted, these overloads are also completely implementable as literal one-liners on top of the existing API surface area:
avivanoff commentedon Oct 23, 2019
@stephentoub, can we at least get documentation updated that it is OK to use WindowsIdentity.RunImpersonated with asynchronous code?
davidfowl commentedon Oct 23, 2019
@stephentoub I'm going to mark this API as ready for review.
terrajobst commentedon Nov 26, 2019
Video
Asyncsuffix would make senseavivanoff commentedon Jan 27, 2020
@stephentoub, I am still trying to get a clear answer whether this works on full framework. Related issue has been sitting there for a while, and documentation has not been updated, either.
avivanoff commentedon Mar 19, 2020
Documentation has finally been updated.