Below are the software/concepts used in this document.
- Visual Studio 2019
- Razor Pages
- Windows Authentication
- .Net Core 2.0
- Net Core Web Application
- C# Language
Introduction
In .NET Framework applications, there are multiple ways to impersonate a user. However, in .NET Core Razor pages, I was not able to find any easier and more straightforward way to achieve the same.
In my project, I have chosen Windows Authentication for managing the logins. However, some of the methods were to be elevated so, that it can execute with a user who has a higher access level.
In order to achieve this, I found a way using WindowsIdentity.RunImpersonated() method which is provided by the namespace System.Security.Principal. Below is the step by step description on how to achieve this.
Open your project in Visual Studio 2019
In my case, I am opening the earlier-created project where Razor pages are present.

Call Method using WindowsIdentity.RunImpersonated ()
In my example, I want to call a method with impersonation in custom Razor page named “Index.cshtml” under “Customers” folder.
Open Index.cshtml.cs file and insert the below code.
- [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
- public static extern bool LogonUser(String Username, String Domain, String Password, int LogonType, int LogonProvider, out SafeAccessTokenHandle Token);
Here, we are using the LogonUser method, which would take user id, password, and domain of the user that we want to use for executing the method. The result of this LogonUser method is that it would provide a handle to an access token.

- const int LOGON32_PROVIDER_DEFAULT = 0;
- //This parameter causes LogonUser to create a primary token.
- const int LOGON32_LOGON_INTERACTIVE = 2;
- // Call LogonUser to obtain a handle to an access token.
- SafeAccessTokenHandle safeAccessTokenHandle;
- bool returnValue = LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeAccessTokenHandle);
- WindowsIdentity.RunImpersonated(safeAccessTokenHandle, () => {
- Var impersonatedUser = WindowsIdentity.GetCurrent().Name;
- //--- Call your Method here…….
- });
That is it. I hope you have learned something new from this article and will utilize this in your work.

Brian.KiserPosted Jul 7, 2021, 9:05 PM
I have really been struggling with impersonation in .net core. Thank you so much! This was incredibly helpful and readable.
arvind kumar sharmaPosted Feb 15, 2021, 4:38 PM
Could you please provide source code for impersonation in dot net core