mattjohnsonpint / simpleimpersonation Goto Github PK
View Code? Open in Web Editor NEWSimple Impersonation Library for .Net
License: MIT License
Simple Impersonation Library for .Net
License: MIT License
I am trying to use your code to kick off Selenium chromedriver in a Run As environment.
When I use the following code:
var credentials = new UserCredentials(".", "XXXXXXX", "XXXXXXX");
Impersonation.RunAsUser(credentials, LogonType.Unlock, () =>
{
IWebDriver driver2 = new ChromeDriver("C:\\Selenium\\Drivers\\");
driver2.Url = "https://google.com";
driver2.Manage().Window.Maximize();
driver2.Quit();
});
If i use anything other than "LogonType.Interactive,LogonType.Unlock " it runs the driver and goes through the steps (albeit, not run as the XXXXXXX User. but as my account).
when i try and run it with LogonType.Interactive or LogonType.Unlock, I get the following error:
Message:
Test method IsmSearchAutoTesting.UnitTest1.openClose threw exception:
System.ComponentModel.Win32Exception: The directory name is invalid
Stack Trace:
at Process.StartWithCreateProcess(ProcessStartInfo startInfo)
at Process.Start()
at DriverService.Start()
at DriverServiceCommandExecutor.Execute(Command commandToExecute)
at RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
at RemoteWebDriver.ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
at ChromeDriver.ctor(ChromeDriverService service, ChromeOptions options, TimeSpan commandTimeout)
at ChromeDriver.ctor(String chromeDriverDirectory, ChromeOptions options)
at ChromeDriver.ctor(String chromeDriverDirectory)
at <>c.<openClose>b__4_0() in UnitTest1.cs line: 157
at <>c__DisplayClass0_0.<RunAsUser>b__0(SafeAccessTokenHandle _)
at <>c__DisplayClass4_0.<RunImpersonated>b__0()
at WindowsIdentity.RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action)
at Impersonation.RunImpersonated(SafeAccessTokenHandle tokenHandle, Action`1 action)
at Impersonation.RunAsUser(UserCredentials credentials, LogonType logonType, Action action)
at UnitTest1.openClose() in UnitTest1.cs line: 153
Any idea what i could be missing?
I have a remote VPS. I created a local user on that VPS. When I am trying to connect I am getting
The user name or password is incorrect
. When I test the credentials though by opening windows explorer on my local pc and trying to connect to that shared folder ("\IPAddressOfTheVPS) it seems they are correct.
My code is the following:
var credentials = new UserCredentials("\IPAddressOfTheVPS", user, pass);
Impersonation.RunAsUser(credentials, LogonType.Network, () =>
{
});
I use something like this to load user profile. It could be added to SimpleImpersonation.
internal class ImpersonationHelper
{
/// <summary>
/// Profile info.
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct PROFILEINFO
{
public static readonly int SizeOf = Marshal.SizeOf(typeof(PROFILEINFO));
public int dwSize; // Set to sizeof(PROFILEINFO) before calling
public int dwFlags; // See PI_ flags defined in userenv.h
public string lpUserName; // User name (required)
public string lpProfilePath; // Roaming profile path (optional, can be NULL)
public string lpDefaultPath; // Default user profile path (optional, can be NULL)
public string lpServerName; // Validating domain controller name in netbios format (optional, can be NULL but group NT4 style policy won't be applied)
public string lpPolicyPath; // Path to the NT4 style policy file (optional, can be NULL)
public IntPtr hProfile; // Filled in by the function. Registry key handle open to the root.
}
/// <summary>
/// Load user profile.
/// </summary>
/// <param name="hToken"></param>
/// <param name="lpProfileInfo"></param>
/// <returns></returns>
[DllImport("Userenv.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool LoadUserProfile(
IntPtr hToken, // user token
ref PROFILEINFO lpProfileInfo // profile
);
/// <summary>
/// Unload user profile.
/// </summary>
/// <param name="hToken"></param>
/// <param name="hProfile"></param>
/// <returns></returns>
[DllImport("Userenv.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool UnloadUserProfile(
IntPtr hToken, // user token
IntPtr hProfile // handle to registry key
);
/// <summary>
/// Load user profile.
/// </summary>
/// <param name="token"></param>
/// <param name="userName"></param>
/// <returns></returns>
public static SafeAccessTokenHandle LoadUserProfile(IntPtr token, string userName)
{
PROFILEINFO profileInfo = new PROFILEINFO();
profileInfo.dwSize = PROFILEINFO.SizeOf;
profileInfo.lpUserName = userName;
profileInfo.dwFlags = 1;
bool loadSuccess = LoadUserProfile(token, ref profileInfo);
if (!loadSuccess)
{
int error = Marshal.GetLastWin32Error();
Console.WriteLine("LoadUserProfile() failed with error code: " +
error);
throw new Win32Exception(error);
}
if (profileInfo.hProfile == IntPtr.Zero)
{
int error = Marshal.GetLastWin32Error();
Console.WriteLine(
"LoadUserProfile() failed - HKCU handle was not loaded. Error code: " +
error);
throw new Win32Exception(error);
}
return new SafeAccessTokenHandle(profileInfo.hProfile);
}
}
UserCredentials credentials = new UserCredentials(userName, password);
Impersonation.RunAsUser(credentials, LogonType.NetworkCleartext, (safeTokenHandle) =>
{
IntPtr loginHandle = safeTokenHandle.DangerousGetHandle();
using (SafeAccessTokenHandle profileHandle = ImpersonationHelper.LoadUserProfile(loginHandle, userName))
{
try
{
}
finally
{
ImpersonationHelper.UnloadUserProfile(loginHandle, profileHandle.DangerousGetHandle());
}
}
});
This is the code I use:
public void ControlService(string host, string username, string password, string name, string action)
{
var credentials = new UserCredentials(host, username, password);
Impersonation.RunAsUser(credentials, SimpleImpersonation.LogonType.Interactive, () =>
{
ServiceControllerPermission scp = new ServiceControllerPermission(ServiceControllerPermissionAccess.Control, host, name);
scp.Assert();
ServiceController sc = new ServiceController(name, host);
TimeSpan timeout = new TimeSpan(0, 0, 30);
switch (action)
{
case "start":
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, timeout);
break;
case "stop":
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
break;
default:
string msg = String.Format("Unknown action: '{0}'", action);
throw new Exception(msg);
}
});
}
The .net program is startet as a normal user, when I now parse the local admin account information to the function above and tell him to start / stop etc a service it says accees denied.
Error messages:
InvalidOperationException: Cannot open Adguard Service service on computer 'DRAGON-BASE'.
and:
Win32Exception: Zugriff verweigert [which means accees denied]
Any ideas?
It'd be great if we could impersonate built in accounts as well. Perhaps along the lines of:
http://geek.hubkey.com/2008/02/impersonating-built-in-service-account.html
Is there any way to wrap a call to Activator.CreateInstance()
against a remote machine with alternate credentials? No matter which value for LogonType
I pass, I get Access Denied.
using (Impersonation.LogonUser(domain, username, password, LogonType.Interactive))
{
try
{
Type t = Type.GetTypeFromProgID("Microsoft.Update.Session", hostname, true);
var comobj = Activator.CreateInstance(t); // <== throws UnauthorizedAccessException
UpdateSession session = (UpdateSession) comobj;
IUpdateSearcher updateSearcher = session.CreateUpdateSearcher();
var count = updateSearcher.GetTotalHistoryCount();
...
This works fine from Powershell if I start the prompt as a different user, by the way:
PS C:\WINDOWS\system32> $updatesession = [activator]::CreateInstance([type]::GetTypeFromProgID("Microsoft.Update.Session", $hostname))
Was wondering if you'd be willing to add support to impersonate the currently logged in user without credentials.
Example. I have a windows service running and would like to impersonate the user that is currently logged in because the service is running under the windows system account. I understand now i could currently still use this library but it would require knowing the username and password of each and every user. I found this library
https://github.com/murrayju/CreateProcessAsUser where they get the user token through WTSEnumerateSessions to get the active session id then WTSQueryUserToken to retrieve the user token.
Hi and thanks, @mj1856, for this great library! My sys admin has created a managed service account (MSA), which is tied to a machine and has no visible password. That account has read/write permissions to a folder on the network where I need to write files to from an MVC C# app.
I've created a question about this on StackOverflow: https://stackoverflow.com/questions/53783296/write-files-to-network-drive-from-iis-using-managed-service-account
Is it possible to impersonate an MSA for this purpose? I've tried this code:
var cred = new UserCredentials("dot", "msa-pims-dev$", "");
Impersonation.RunAsUser(cred, LogonType.Batch, () =>
{
System.IO.File.WriteAllText(@"\\SomeUncPath\Reports", "sample text");
}
);
The above throws this:
System.ArgumentException: Password cannot be empty or consist solely of whitespace characters. Parameter name: password
Thanks.
Hello,
I was wondering if there were any plans to support Linux with SimpleImpersonation? I'm receiving the following error when trying to run it:
Unable to load DLL 'advapi32.dll': The specified module or one of its dependencies could not be found.
My company is migrating away from Windows to Linux and this library has been supremely awesome to use. I'd really prefer to try and continue with it as opposed to having to look for workarounds.
Thanks,
Victor
Is it possible to get an overload to pass a username in UPN syntax (i.e. [email protected]) instead of the SAM name (i.e. DOMAIN\username)?
using (Impersonation.LogonUser(upn, password, LogonType.Interactive))
{ ... }
I'm starting to use Windows 2016 domain controllers and servers, and I can't guarantee there will be a SAM-compatible name forever.
The Assembly is unsigned and should contain a public key token to work with.
I am trying to access UNC but it is not working on Framework 4.7.2/Core 2.2 version. If I try old method with WindowsImpersonationContext it is working but Core is not supporting WindowsImpersonationContext.
Hello :)
I am trying to start a process with different rights from the inside of an windows service.
If i impersonate like this:
Impersonation.RunAsUser(credentials, LogonType.Interactive, () => {
ProcessStartInfo info = new ProcessStartInfo(cmd_name, parameters);
info.UseShellExecute = false;
info.CreateNoWindow = true;
info.RedirectStandardOutput = true;
console.StartInfo = info;
console.Start();
message = console.StandardOutput.ReadToEnd();
});
the process will still run as local system. If i set the Credentials also in the ProcessStartInfo Class, i get an Access Denied.
Currently i am using an implementation of the native call "CreateProcessAsUserW" but i was looking for an working solution with the Process Class of .NET
Thank you :)
Caused error:
System.IO.FileLoadException: Could not load file or assembly 'SimpleImpersonation, Version=2.0.1.27158, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)
Because of this it not possible to use with signed assemblies
Great little library. Any chance of creating a signed version of it on NuGet?
I've been running in to a weird issue on my VB Windows Form project. When calling the LogonUser, it tells me there is no source available:
Locating source for 'c:\Dev\SimpleImpersonation\SimpleImpersonation\Impersonation.cs'. Checksum: MD5 {6c 71 cb 29 b2 c9 b5 bb a7 f6 15 1b 92 4e d6 71}
The file 'c:\Dev\SimpleImpersonation\SimpleImpersonation\Impersonation.cs' does not exist.
Looking in script documents for 'c:\Dev\SimpleImpersonation\SimpleImpersonation\Impersonation.cs'...
Looking in the projects for 'c:\Dev\SimpleImpersonation\SimpleImpersonation\Impersonation.cs'.
The file was not found in a project.
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\crt\src'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\src\mfc'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\src\atl'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\include'...
The debug source files settings for the active solution indicate that the debugger will not ask the user to find the file: c:\Dev\SimpleImpersonation\SimpleImpersonation\Impersonation.cs.
The debugger could not locate the source file 'c:\Dev\SimpleImpersonation\SimpleImpersonation\Impersonation.cs'.
I have to re-install the NuGet package for this to work. I'm not sure what causes this behavior, but it sometimes happens after I make a few simple, unrelated changes in my project and save. It appears to by referencing a file on your PC ("c:\Dev...")? I'm concerned this may happen on a Released build. I'm getting close to releasing it and hope to find a solution.
Thanks and great work!
What is the purpose of putting the handle in a SafeHandle and returning it to the caller via an out
parameter? If you look at the source for WindowsIdentity.Impersonate it looks like it already duplicates the handle into a safe handle.
Hello,
Thanks for the wonderful work, it works flawlessly on my local laptop, but when I scheduled it in Autosys, it always fails. I even stripped out all the code to barebone like below and still fails. As soon as I remove SimpleImpersonation from my console app, it works. I have some other console apps that are not using SimpleImpersonation and they all work fine in autosys. Any suggestions?
namespace ConsoleAppNetCore_CopyTable
{
using System.Data.SqlClient;
class Program
{
static void Main()
{
}
}
}
When executing the RunAsUser method, if T is IEnumerable, and the Func passed in as the function parameter performs yield return
, then the RunAsUser method immediately returns the IEnumerable, and the impersonated user context is already disposed by the time the first yield return
statement executes.
Consider the following example console app:
using System;
using System.Collections.Generic;
using SimpleImpersonation;
namespace SimpleImpersonationTests
{
class Program
{
private static UserCredentials _UserCredentials = new UserCredentials("TestUsername", "password");
private static LogonType _LogonType = LogonType.Interactive;
static void Main(string[] args)
{
Console.WriteLine($"Running {nameof(RunEnumerableTest1)}:");
WriteUsernamesToConsole(RunEnumerableTest1());
Console.WriteLine($"\nRunning {nameof(RunEnumerableTest2)}:");
WriteUsernamesToConsole(RunEnumerableTest2());
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
private static void WriteUsernamesToConsole(IEnumerable<string> usernames)
{
foreach (string username in usernames)
{
Console.WriteLine(username);
}
}
private static IEnumerable<string> GetCurrentUsers()
{
yield return Environment.UserName;
yield return Environment.UserName;
yield return Environment.UserName;
}
private static IEnumerable<string> RunEnumerableTest1() =>
Impersonation.RunAsUser(_UserCredentials, _LogonType, () =>
{
Console.WriteLine("Current user = " + Environment.UserName);
return GetCurrentUsers();
});
private static IEnumerable<string> RunEnumerableTest2() =>
Impersonation.RunAsUser(_UserCredentials, _LogonType, GetCurrentUsers);
// This is not possible, due to yield inside an anonymous function
//private static IEnumerable<string> RunEnumerableTest3() =>
// Impersonation.RunAsUser(_UserCredentials, _LogonType, () =>
// {
// Console.WriteLine("Current user = " + Environment.UserName);
// foreach (string username in GetCurrentUser())
// {
// yield return username;
// }
// });
}
}
Output of the above:
Running RunEnumerableTest1:
Current user = TestUsername
ryanc
ryanc
ryancRunning RunEnumerableTest2:
ryanc
ryanc
ryanc
Press enter to exit.
I wonder if a new method could be added to support yielded IEnumerable's? Where it would use a foreach
to execute the iterator and keep the context alive during iteration. Maybe like:
public IEnumerable<T> RunEnumerableAsUser<T>(UserCredentials userCredentials, LogonType logonType, Func<IEnumerable<T>> function)
Excellent library. However, since it isn't strongly named, I'm having problems using it within our code base.
First -- great super-simple library!
My issue is no longer an issue. Combination of weird things, but I got the right sequence for it to work.
Great library!!!
I am invoking a method on a WCF service that calls Process.Start()
. This service is hosted in a console application, which is started remotely via WMI and runs as an administrative user.
When I invoke the service method, it kicks off a setup.exe
using Process.Start()
. This setup.exe
is also running as the administrative user mentioned above. So far so good.
This setup.exe
has a C++ .dll which connects to SQL Server using integrated security. In SQL Server, we see the connection from "NT Authority\Anonymous Logon" and not the administrative user.
I don't think this is in any way related to SimpleImpersonation, because WMI is actually doing the login here, but I figured I'd ask here anyway ;)
My WMI connection options:
var opts = new ConnectionOptions
{
Username = username,
Password = password,
Impersonation = ImpersonationLevel.Impersonate
};
(This is a bit convoluted, I know. Would a sequence diagram help here?)
Based on the documentation for this project:
"If impersonation fails, it will throw a custom ImpersonationException, which has the following properties:..."
While attempting to debug an issue, I noticed that even passing in invalid credentials to RunAsUser, it would still execute the Action (as the current user) if LogonType was NewCredentials.
I tested this scenario in a simple ConsoleApp:
using System;
namespace SimpleImpersonationFailureTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// Change this to anything other than NewCredentials and it successfully throws an exception
SimpleImpersonation.LogonType logonType = SimpleImpersonation.LogonType.NewCredentials;
SimpleImpersonation.Impersonation.RunAsUser(new SimpleImpersonation.UserCredentials("baddomain", "badusername", "badpassword"), logonType, () =>
{
//If I get here, that's a problem...
Console.WriteLine("Goodbye World!");
});
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
}
}
My gut says LOGON32_LOGON_NEW_CREDENTIALS is the core of the issue, and there may not be a reasonable solution for trapping invalid credentials with this one LogonType. If so, then the documentation should at least be updated to reflect that.
I'm getting this error when I try to impersonate an account for File.Copy(..)
I'm trying to update the user and password on a windows service from an application that is ran without administrator rights. On Windows 7 I can impersonate the domain admin and then call sc.exe with no problems. Under Windows 10 even though I'm impersonating a domain admin I can't make these changes unless I right click and run the app as administrator. UAC is turned off. Have you ran into anything like that with windows 10? Your library is great BTW.
I have a SO question out there as well https://stackoverflow.com/questions/51862476/net-impersonation-not-working
It's possible to receive an exception of "SafeHandle cannot be null", due to the way the native LogonUser
is defined.
We're currently using the same P/Invoke declaration as the MSDN sample code.
Per Hans Passant, this was incorrect and we should be returning an IntPtr
.
The NuGet package as it is published on NuGet.org (1.1.0 as of writing) contains a .nuspec with no file references - neither for net20 nor net40.. so whenever adding the package to a project, nothing really happens.
The .nuspec in the repository itself appears to only have a net20 section and I am not entirely sure how you build/package & publish the package (manually or i.e. via a ci / build system) but while developers can manually add a reference to the assembly, it is a bit confusing.. :)
Hi, thank you for your work.
I want to know if it is possible to impersonate with the current connected user in a MVC application?
I cannot create a new UserCredentials, i don't know the user password (and don't want to know it).
Is it possible to use CredentialCache.DefaultCredentials or CredentialCache.DefaultNetworkCredentials as a UserCredentials?
Thx, Julien Legrand
I'm trying to access the network printers by doing impersonation (using this code) to print a pdf document from IIS (wcf application). Since my wcf application run under 'LocalSystem' app pool identity, i need to do the impersonation. But Printing doesn't work with this impersonation, even I can't list out the network printers also.
If I change the logonType to 'LOGON32_LOGON_INTERACTIVE' and logonProvider as 'LOGON32_PROVIDER_DEFAULT' then I can list out the network printers but when I send the document to the printer it doesn't print. it shows with Size empty in the print queue. Any Idea please???
Impersonation Code:
` [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public class Impersonation : IDisposable
{
private readonly SafeTokenHandle _handle;
private readonly WindowsImpersonationContext _context;
bool disposed = false;
// constants from winbase.h
const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_LOGON_NETWORK = 3;
const int LOGON32_LOGON_BATCH = 4;
const int LOGON32_LOGON_SERVICE = 5;
const int LOGON32_LOGON_UNLOCK = 7;
const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_PROVIDER_WINNT35 = 1;
const int LOGON32_PROVIDER_WINNT40 = 2;
const int LOGON32_PROVIDER_WINNT50 = 3;
public Impersonation(ImpersonateUserDetails user) : this(user.Domain, user.UserName, user.Password)
{ }
public Impersonation(string domain, string username, string password)
{
// if domain name was blank, assume local machine
if (string.IsNullOrEmpty(domain))
domain = System.Environment.MachineName;
var ok = LogonUser(username, domain, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out this._handle);
if (!ok)
{
var errorCode = Marshal.GetLastWin32Error();
throw new ApplicationException(string.Format("Could not impersonate the elevated user. LogonUser returned error code {0}.", errorCode));
}
this._context = WindowsIdentity.Impersonate(this._handle.DangerousGetHandle());
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
this._context.Dispose();
this._handle.Dispose();
}
disposed = true;
}
~Impersonation()
{
Dispose(false);
}
[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);
sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle()
: base(true) { }
[DllImport("kernel32.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
}
public class ImpersonateUserDetails
{
public string UserName { get; set; }
public string Password { get; set; }
public string Domain { get; set; }
}`
Printing code to Network Printer:
using (new Impersonation(domain, username, password)) { PrinterUtility pu = new PrinterUtility(); pu.Print(fileName, "TestFile.pdf", printerName); }
PrinterUtility Class:
` using System;
using System.Drawing.Printing;
using System.IO;
using System.Drawing;
using System.Text;
namespace NetworkPrintWCF
{
public class PrinterUtility
{
private Font printFont;
private StreamReader streamToPrint;
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
String line = null;
// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height /
printFont.GetHeight(ev.Graphics);
// Iterate over the file, printing each line.
while (count < linesPerPage &&
((line = streamToPrint.ReadLine()) != null))
{
yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
count++;
}
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}
// Print the file.
public void Print(string filePath, string fileName, string printerNetworkPath)
{
try
{
streamToPrint = new StreamReader(filePath);
try
{
var printerSettings = new PrinterSettings
{
PrinterName = printerNetworkPath,
PrintFileName = fileName,
PrintRange = PrintRange.AllPages,
};
printerSettings.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
printFont = new Font("Arial", 10);
PrintDocument pd = new PrintDocument();
pd.DocumentName = fileName;
pd.PrinterSettings = printerSettings;
//pd.PrintController = new StandardPrintController();
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
// Print the document.
pd.Print();
}
finally
{
streamToPrint.Close();
}
}
catch
{
throw;
}
}
}
}`
I'm sure this is the problem with impersonation. because If I change my application's app pool identity to a domain user (same domain user credential I was trying to use to impersonate) then printing works fine.
Web Server Environment: Windows Server 2012 R2, IIS 8.5.
But with this impersonationated code, printing fails. Document sows up in print queue with NO size (kindly refer attached image)
Need unit tests. This may requires some complex setup, given the nature of this library.
Hello,
In my tests I have access to a shared directory on the network, the credentials I use to access it are different from the ones I use on my PC. My code looks like this:
var credentials = new UserCredentials(domain, user, pass);
Impersonation.RunAsUser(credentials, LogonType.Interactive, () =>
{
File.Copy(FullPathAndFileName, FullPathDestiny);
});
But I always get the same error: Trust relationship between this workstation and the primary domain failed.
Can anyone help me how to solve this?
PS- If I remove the domain from the credentials I receive the invalid user or password msg, but through windows explorer I can access the share with these credentials.
Currently whenever impersonation cannot be performed / completed an System.ApplicationException is thrown with the underlying error code only available inside the generic string.. which makes it quite hard from a developer point of view to find out what exactly is wrong and handle it appropriately.
It would be neat to get the underlying cause when using the library, i.e. via throwing a Win32Exception instead (I'll send over a PR shortly).
Hello all,
I am new to development and was hoping someone could point me in the right direction. My code works fine when I run it within VS, however, when I published it as a self-contained package and run the .exe file, I am getting the error message below:
Unhandled Exception: System.IO.FileNotFoundException
at ConsoleAppNetCore_CopyTable.Program.<>c.
The guidance from the .NET team has changed, and is now clear that OSS libraries should be strong named.
https://docs.microsoft.com/en-us/dotnet/standard/library-guidance/strong-naming
This will be a breaking change
https://haacked.com/archive/2012/02/16/changing-a-strong-name-is-a-major-breaking-change.aspx/
I am trying to copy files from my local machine to a share on a remote machine. I am impersonating a domain user, and this user has full permissions to the remote machine's share.
using (Impersonation.LogonUser(string.Empty, _username, _password, LogonType.Interactive))
{
...
foreach (var fi in source.GetFiles())
{
Logger.Info(@"Copying {0} to {1}\{2}", fi.FullName, target, fi.Name);
var destFile = new FileInfo(Path.Combine(target.ToString(), fi.Name));
fi.CopyTo(destFile.FullName, true);
}
...
}
The CopyTo function is throwing an IOException with the message "The specified network name is no longer available".
The runtime values are (redacted):
fi.Name = C:\xxx\xxx\xxx\xxx\Cmc.Installer\Cmc.Installer.Agent.Console\bin\Debug\Cmc.Installer.Agent.Console.exe
destFile.FullName = \servername\sharename\Cmc.Installer.Agent.Console.exe
I am also passing string.Empty as the domain because _username is in UPN (user@domain) form.
Is there a way to get this to work reliably? I am using .NET 4.5.1 on Windows 7 and the remote machine is Windows Server 2008 R2.
Not sure what I am doing wrong, but the impersonation does not seem to work in my environment. I'm not getting any errors thrown from a call to LogonUser() itself, but I am getting access denied errors when I actually try to read or write a file on a network fileshare. I am definitely passing in the correct credentials to LogonUser(). I have observed that WindowsIdentity.GetCurrentUser().Name always returns the "Guest" account.
using (Impersonation.LogonUser(ConfigurationManager.AppSettings["CrsDimFileShareDomainName"],
ConfigurationManager.AppSettings["CrsDimFileShareUserName"],
ConfigurationManager.AppSettings["CrsDimFileSharePassword"],
LogonType.Network))
{
I am using this to write files to a network file share inside a .net core 3.1 web application (with logontype.newcredential). Files do get written to the file server, and the owner of the files matches the impersonated user. However if I get the value of the Windows.Identity.GetCurrent().Name inside the RunAsUser block, it returns the user who is running the application. My head is swimming with all the documents I have read about impersonating users, so I am not sure if this is the expected result, or if I am not really impersonating the user correctly (to me the correct document owner implies that I am, but the GetCurrent().Name implies that I am not). Any pointers to explain this would be appreciated.
Is DNC support possible on Windows OS?
I am trying to access a network share that has access limited to users part of the "Authenticated Users" group. I am running a process as SYSTEM and impersonating as a local user.
var user = new SimpleImpersonation.UserCredentials($@".\{Username}", Password);
SimpleImpersonation.Impersonation.RunAsUser(user, SimpleImpersonation.LogonType.NewCredentials, () => {
var ident = WindowsIdentity.GetCurrent();
Logger.Info($"Name={ident.Name}");
Logger.Info($"IsAuthenticated={ident.IsAuthenticated}");
Logger.Info($"Level={ident.ImpersonationLevel}");
foreach (var claim in ident.Claims)
{
Logger.Info($"Claim={claim}");
}
foreach (var file in Directory.EnumerateFileSystemEntries(@"\\SERVER\Shared"))
{
Logger.Info($@">>> {file}");
}
})
Output:
Name=NT AUTHORITY\SYSTEM
IsAuthenticated=True
Level=Impersonation
Claim=http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: NT AUTHORITY\SYSTEM
Claim=http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid: S-1-5-18
Claim=http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid: S-1-1-0
Claim=http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid: S-1-5-32-559
Claim=http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid: S-1-5-32-545
Claim=http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid: S-1-5-4
Claim=http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid: S-1-2-1
Claim=http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid: S-1-5-11
Claim=http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid: S-1-5-15
Claim=http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid: S-1-5-32-544
System.UnauthorizedAccessException: Access to the path '\\SERVER\Shared' is denied.
I see that current identity has S-1-5-11 (Authenticated Users), but that apparently isn't used for the network connection. Any ideas on how to have the network credentials be part of that group?
I'm trying to execute some PS scripts as another user.
Here is the function :
public string GetSizeLecteurH(string GID, string Serveur)
{
using (SimpleImpersonation.Impersonation.LogonUser(Login.Split('\\')[0], Login.Split('\\')[1], Password, SimpleImpersonation.LogonType.Interactive))
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript(TestLecteurH);
PowerShellInstance.AddParameter("GID", GID);
PowerShellInstance.AddParameter("Serveur", Serveur);
//PowerShellInstance.AddParameter("credential", Credential);
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
try
{
if (!PowerShellInstance.HadErrors) return PSOutput.Count > 0 ? PSOutput.ElementAt(0).ToString() : "pas de retour";
else return PowerShellInstance.Streams.Error.ElementAt(0).Exception + "";
}
catch (Exception e)
{
Debug.WriteLine(e.StackTrace);
return "inexistant";
}
}
}
}
I'm providing a string for the Login var as "domain\login".
When I execute this code, the Collection returns a "System.Security.SecurityException" : Requested registry access is not allowed
However it will works if I do not use the Impersonation and just run the entire script as the identity I'm passing to the LogonUser function.
I'm a bit lost, how can I avoid this error ?
Not really an issue, but more a question :) Was thinking to post on SO first, but decided this is a more appropriate place for such a question...
I have a code running in a loop repeatedly many times, doing some work not requiring impersonation. The result is the IO File operation that I only want to do impersonated. When I do wrap this particular operation in an impersonated call it takes a lot of time since I assume it requests a token with each loop iteration. Putting the whole loop inside the impersonation makes the whole thing look ugly, especially that it's not the only such a scenario in my code... I was hoping to do as less as possible code impersonated since it's a user with kind of elevated privileges.
I was thinking about putting the impersonator to a different dedicated thread/process and keeping it open, waiting for new tasks... Then read about problems with asynchronous tasks and found this relative fresh solution (from links in #32).
Do you have any suggestions for the best strategy in my case? What do u think about asynchronous task scheduler I posted above?
Hi,
I tried to compile the project but I receive some syntax exceptions. I am absolutely not strong with C Sharp so can you please help me with what is going on?
Msbuild seems to struggle with
c:\playground\SimpleImpersonation-master>c:\windows\Microsoft.NET\Framework64\v4.0.30319\msbuild SimpleImpersonation.sln /t:Build /p:Configuration=Release
Microsoft (R) Build Engine version 4.6.1038.0
[Microsoft .NET Framework, version 4.0.30319.42000]
Copyright (C) Microsoft Corporation. All rights reserved.Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
Build started 7/15/2016 4:37:35 PM.
Project "c:\playground\SimpleImpersonation-master\SimpleImpersonation.sln" on node 1 (Build target(s)).
ValidateSolutionConfiguration:
Building solution configuration "Release|Any CPU".
Project "c:\playground\SimpleImpersonation-master\SimpleImpersonation.sln" (1) is building "c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj" (2) on node 1 (default targets).
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Common.targets(983,5): warning MSB3644: The reference assemblies for framework ".NETFramework,Version=v4.0,Profile=Client" were not found. To resolve this, install the SDK or Targeting Pack for this framework version or retarget your application to a version of the framework for which you have the SDK or Targeting Pack installed. Note that assemblies will be resolved from the Global Assembly Cache (GAC) and will be used in place of reference assemblies. Therefore your assembly may not be correctly targeted for the framework you intend. [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Common.targets(983,5): warning MSB3644: The reference assemblies for framework ".NETFramework,Version=v4.0" were not found. To resolve this, install the SDK or Targeting Pack for this framework version or retarget your application to a version of the framework for which you have the SDK or Targeting Pack installed. Note that assemblies will be resolved from the Global Assembly Cache (GAC) and will be used in place of reference assemblies. Therefore your assembly may not be correctly targeted for the framework you intend. [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Common.targets(1605,5): warning MSB3270: There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project. [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
GenerateTargetFrameworkMonikerAttribute:
Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files.
CoreCompile:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Csc.exe /noconfig /nowarn:1701,1702 /nostdlib+ /errorreport:prompt /warn:4 /doc:bin\Release\SimpleImpersonation.xml /define:TRACE /highentropyva- /reference:C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll /reference:C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll /reference:C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll /debug:pdbonly /filealign:512 /optimize+ /out:obj\Release\SimpleImpersonation.dll /target:library /utf8output Impersonation.cs ImpersonationException.cs LogonType.cs NativeMethods.cs Properties\AssemblyInfo.cs SafeTokenHandle.cs "C:\Users\afr\AppData\Local\Temp.NETFramework,Version=v4.0,Profile=Client.AssemblyAttributes.cs"
ImpersonationException.cs(27,30): error CS1002: ; expected [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
ImpersonationException.cs(27,49): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
ImpersonationException.cs(27,64): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
ImpersonationException.cs(27,75): error CS1519: Invalid token ';' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
ImpersonationException.cs(32,36): error CS1002: ; expected [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
ImpersonationException.cs(32,55): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
ImpersonationException.cs(32,70): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
ImpersonationException.cs(32,87): error CS1519: Invalid token ';' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
Done Building Project "c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj" (default targets) -- FAILED.
Project "c:\playground\SimpleImpersonation-master\SimpleImpersonation.sln" (1) is building "c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj" (3) on node 1 (default targets).
CoreCompile:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Csc.exe /noconfig /nowarn:1701,1702 /nostdlib+ /errorreport:prompt /warn:4 /doc:bin\Release\SimpleImpersonation.xml /define:TRACE /highentropyva- /reference:C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorlib.dll /reference:C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.dll /debug:pdbonly /filealign:512 /optimize+ /out:obj\Release\SimpleImpersonation.dll /target:library /utf8output ..\SimpleImpersonation\Impersonation.cs ..\SimpleImpersonation\ImpersonationException.cs ..\SimpleImpersonation\LogonType.cs ..\SimpleImpersonation\NativeMethods.cs ..\SimpleImpersonation\Properties\AssemblyInfo.cs ..\SimpleImpersonation\SafeTokenHandle.cs
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(27,30): error CS1002: ; expected [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(27,49): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(27,64): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(27,75): error CS1519: Invalid token ';' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(32,36): error CS1002: ; expected [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(32,55): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(32,70): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(32,87): error CS1519: Invalid token ';' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
Done Building Project "c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj" (default targets) -- FAILED.
Done Building Project "c:\playground\SimpleImpersonation-master\SimpleImpersonation.sln" (Build target(s)) -- FAILED.Build FAILED.
"c:\playground\SimpleImpersonation-master\SimpleImpersonation.sln" (Build target) (1) ->
"c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj" (default target) (2) ->
(GetReferenceAssemblyPaths target) ->
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Common.targets(983,5): warning MSB3644: The reference assemblies for framework ".NETFramework,Version=v4.0,Profile=Client" were not found. To resolve this, install the SDK or Targeting Pack for this framework version or retarget your application to a version of the framework for which you have the SDK or Targeting Pack installed. Note that assemblies will be resolved from the Global Assembly Cache (GAC) and will be used in place of reference assemblies. Therefore your assembly may not be correctly targeted for the framework you intend. [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Common.targets(983,5): warning MSB3644: The reference assemblies for framework ".NETFramework,Version=v4.0" were not found. To resolve this, install the SDK or Targeting Pack for this framework version or retarget your application to a version of the framework for which you have the SDK or Targeting Pack installed. Note that assemblies will be resolved from the Global Assembly Cache (GAC) and will be used in place of reference assemblies. Therefore your assembly may not be correctly targeted for the framework you intend. [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]"c:\playground\SimpleImpersonation-master\SimpleImpersonation.sln" (Build target) (1) ->
"c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj" (default target) (2) ->
(ResolveAssemblyReferences target) ->
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Common.targets(1605,5): warning MSB3270: There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project. [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]"c:\playground\SimpleImpersonation-master\SimpleImpersonation.sln" (Build target) (1) ->
"c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj" (default target) (2) ->
(CoreCompile target) ->
ImpersonationException.cs(27,30): error CS1002: ; expected [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
ImpersonationException.cs(27,49): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
ImpersonationException.cs(27,64): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
ImpersonationException.cs(27,75): error CS1519: Invalid token ';' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
ImpersonationException.cs(32,36): error CS1002: ; expected [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
ImpersonationException.cs(32,55): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
ImpersonationException.cs(32,70): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]
ImpersonationException.cs(32,87): error CS1519: Invalid token ';' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation\SimpleImpersonation.csproj]"c:\playground\SimpleImpersonation-master\SimpleImpersonation.sln" (Build target) (1) ->
"c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj" (default target) (3) ->
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(27,30): error CS1002: ; expected [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(27,49): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(27,64): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(27,75): error CS1519: Invalid token ';' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(32,36): error CS1002: ; expected [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(32,55): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(32,70): error CS1519: Invalid token ')' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]
c:\playground\SimpleImpersonation-master\SimpleImpersonation\ImpersonationException.cs(32,87): error CS1519: Invalid token ';' in class, struct, or interface member declaration [c:\playground\SimpleImpersonation-master\SimpleImpersonation.Net20\SimpleImpersonation.Net20.csproj]3 Warning(s) 16 Error(s)
Time Elapsed 00:00:00.71
The same happens when opening the project using Visual Studio (2010, on a different server). Can you please help me and point me what the issue is?
I tried two systems (one with Windows 10 and one with Windows 2012 Server), both have .net 4.6.1 installed.
I would like to use Impersonation.RunAsUser but I'm not sure how to direct the code to the domain unless it's by name. Should I be able to use IP address like below? FYI I'm not really connecting to 192.168.1.1 that's just a filler.
You'll notice the commented out code. My ultimate goal is to create a link to a network share so that I don't have to keep all our files on the www server.
Do you have any thoughts on the best way to achieve this?
var credentials = new UserCredentials("192.168.1.1", "user", "password");
Impersonation.RunAsUser(credentials, LogonType.Network, () =>
{
//app.UseStaticFiles(new StaticFileOptions
//{
// FileProvider = new PhysicalFileProvider(@"\\192.168.1.1\Images"),
// RequestPath = "/images",
//});
});
I can't access network drives doesn't what LogonType I use.
Example:
User A is default user and can view all network drives but when I start my impersonation as User B, the drives are not available.
Hello,
I have rather a strange issue, I need to ensure user connects to network share with Guest account (passwordless), even if other user is stored in windows credentials. I have tried to RunAsUser Guest with no password, but package does allow this. Is there any solution?
Considering code such as:
Item item = await Impersonation.RunAsUser(credentials, LogonType.NewCredentials, async () =>
{
using (var context = new MyDbContext())
{
return await context.Items.FirstOrDefaultAsync();
}
});
While this looks correct, it appears that the task sometimes runs as if not impersonated. This is being discussed further in dotnet/corefx#24977.
I'll leave this item open for tracking, and discussion of alternatives. In the meantime, I recommend against using impersonation with asynchronous tasks.
I've got an existing function public void DoThing()
I'd like to use an elevated user for some things in do thing and not others. Unfortunately complicated by a using
...
public void DoThing()
{
using(SomeObject x) <-- impersonate user here
{
string s = x.Stuff
WriteToFileSystem(s) <-- do not impersonate user here
}
}
I have the username/password for the impersonate user. But for the WriteToFileSystem
I'd like to use te currect user.
Any ideas on how I could accomplish this?
I realize that refactoring the code here to not WriteToFileSystem
in this function is a better solution. But it doesn't really work in my solution..
I'm hoping for something like this.
var currentUser = GetCurrentUserSomeHow()
Impersonation.RunAsUser(credentials, logonType, () =>
{
using(SomeObject x)
{
string s = x.Stuff;
Impersonation.RunAsUser(currentUser, () =>
{
WriteToFileSystem(s);
}
}
}
I was looking for some projects to make it easy to access a shared network folder. Found yours and David Whitehead's.
He also implemented the impersonation as a middleware.
Need to return the Win32 NativeErrorCode
in the ImpersonationException
instead of the ErrorCode
- which is just an HResult handle.
For example, login failure should be code 1326
, not -2146232832
(0x80131600
)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.