You can use impersonation and the WindowsImpersonationContext
Class to achieve your requirements. The idea is that the application runs with normal permissions, but when you need to access something that has higher permissions, the application can provide the log in details of a user account that has the correct permissions. It would look something like this:
using (ImpersonationManager impersonationManager = new ImpersonationManager())
{
impersonationManager.Impersonate(Settings.Default.MediaAccessDomain,
Settings.Default.MediaAccessUserName, Settings.Default.MediaAccessPassword);
// Perform restricted action as other user with higher permissions here
}
Note that this ImpersonationManager
class is a custom class, so you won't find it on MSDN, but it just uses the SafeTokenHandle
and other code from the linked page:
private SafeTokenHandle safeTokenHandle;
private WindowsImpersonationContext impersonationContext;
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
public void Impersonate(string domain, string username, string password)
{
var isLoggedOn = LogonUser(username, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, 0, out safeTokenHandle);
if (!isLoggedOn)
{
var errorCode = Marshal.GetLastWin32Error();
throw new ApplicationException(string.Format("Could not impersonate the elevated user. The LogonUser method returned error code {0}.", errorCode));
}
impersonationContext = WindowsIdentity.Impersonate(this.safeTokenHandle.DangerousGetHandle());
}