i want to add generic credentials to Credential Manager for a specific user. I tried using impersonation but it gives error "A specified logon session does not exist. It may already have been terminated". When i do not use "impersonation", I can add credentials easily but only for the user that opens the application. Anybody have any suggestion or answer to solve this problem?
My code fragment:
using (var imp = new Impersonation("creduserApp", "creduser", "123*+56"))
{
//I got error after running the following here
foreach (var credential in CredentialManager.EnumerateCrendentials())
{
Console.WriteLine(credential);
}
}
Impersonation Method:
public Impersonation(string domain, string username, string password)
{
var token = ValidateParametersAndGetFirstLoginToken(username, domain, password);
var duplicateToken = IntPtr.Zero;
try
{
if (DuplicateToken(token, 2, ref duplicateToken) == 0)
{
throw new InvalidOperationException("DuplicateToken call to reset permissions for this token failed");
}
var identityForLoggedOnUser = new WindowsIdentity(duplicateToken);
_impersonatedUserContext = identityForLoggedOnUser.Impersonate();
if (_impersonatedUserContext == null)
{
throw new InvalidOperationException("WindowsIdentity.Impersonate() failed");
}
}
finally
{
if (token != IntPtr.Zero)
CloseHandle(token);
if (duplicateToken != IntPtr.Zero)
CloseHandle(duplicateToken);
}
}