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.
Now, put the below code to execute your method with new credentials that has higher access. In my example, I am calling “GetClaimsAsDataTable() method with impersonated user access.
- const int LOGON32_PROVIDER_DEFAULT = 0;
-
- const int LOGON32_LOGON_INTERACTIVE = 2;
-
- SafeAccessTokenHandle safeAccessTokenHandle;
- bool returnValue = LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeAccessTokenHandle);
- WindowsIdentity.RunImpersonated(safeAccessTokenHandle, () => {
- Var impersonatedUser = WindowsIdentity.GetCurrent().Name;
-
- });
Test the files by right-clicking on the Index file and opening it with browser. If you put a breakpoint on the Var impersonatedUser= WindowsIdentity.GetCurrent().Name line which is inside the WindowsIdentity.RunImpersonated method, you will find that it displays the name of the user that has a higher level of access.
That is it. I hope you have learned something new from this article and will utilize this in your work.