Click here to Skip to main content
15,887,365 members
Home / Discussions / C#
   

C#

 
GeneralRe: Customize VS2010 Start Page Pin
RaviRanjanKr16-Nov-10 2:40
professionalRaviRanjanKr16-Nov-10 2:40 
Questionfull text search Pin
annie_bel4-Nov-10 3:31
annie_bel4-Nov-10 3:31 
AnswerRe: full text search Pin
JohnLBevan4-Nov-10 3:53
professionalJohnLBevan4-Nov-10 3:53 
AnswerRe: full text search Pin
Adam R Harris4-Nov-10 4:53
Adam R Harris4-Nov-10 4:53 
QuestionImpersonation using C# Pin
JohnLBevan4-Nov-10 1:45
professionalJohnLBevan4-Nov-10 1:45 
AnswerRe: Impersonation using C# Pin
Adam R Harris4-Nov-10 4:49
Adam R Harris4-Nov-10 4:49 
AnswerRe: Impersonation using C# Pin
Manfred Rudolf Bihy4-Nov-10 5:06
professionalManfred Rudolf Bihy4-Nov-10 5:06 
GeneralRe: Impersonation using C# Pin
JohnLBevan9-Nov-10 5:43
professionalJohnLBevan9-Nov-10 5:43 
That's perfect. Thanks to both of you for the link & code sample; very much appreciated.

I've put this code into a disposable object, so that you can easily swap contexts, using the using statement to control when you impersonate another account. Hopefully this will be of use to anyone following this thread in future.

e.g.
class Program
{
    static void Main(string[] args)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<demo />");
        doc.Save(@"\\server\share\demo1.xml"); //created with owner set to Administrators (assuming current account has access)
        using (Impersonator impersonate = new Impersonator(@"domain\user"))
        {
            doc.Save(@"\\server\share\xjbdemo2.xml"); //created with owner set to domain\user (assuming domain\user has access)
        }
        doc.Save(@"\\server\share\xjbdemo3.xml"); //created with owner set to Administrators (assuming current account has access)

        Console.WriteLine("Done");
        Console.ReadKey();
    }
}





/// &lt;summary&gt;
/// Allows impersonation to be done easily via the code below
/// using (Impersonator impersonate = new Impersonator("domain\user", "pass")
/// {
///     //do stuff as other user
/// }
/// &lt;/summary&gt;
public class Impersonator: IDisposable
{

    #region windows api reference
    #region enums
    //thanks to http://www.pinvoke.net/default.aspx/advapi32.logonuser
    public enum LogonType
    {
        /// &lt;summary&gt;
        /// This logon type is intended for users who will be interactively using the computer, such as a user being logged on
        /// by a terminal server, remote shell, or similar process.
        /// This logon type has the additional expense of caching logon information for disconnected operations;
        /// therefore, it is inappropriate for some client/server applications,
        /// such as a mail server.
        /// &lt;/summary&gt;
        LOGON32_LOGON_INTERACTIVE = 2,

        /// &lt;summary&gt;
        /// This logon type is intended for high performance servers to authenticate plaintext passwords.

        /// The LogonUser function does not cache credentials for this logon type.
        /// &lt;/summary&gt;
        LOGON32_LOGON_NETWORK = 3,

        /// &lt;summary&gt;
        /// This logon type is intended for batch servers, where processes may be executing on behalf of a user without
        /// their direct intervention. This type is also for higher performance servers that process many plaintext
        /// authentication attempts at a time, such as mail or Web servers.
        /// The LogonUser function does not cache credentials for this logon type.
        /// &lt;/summary&gt;
        LOGON32_LOGON_BATCH = 4,

        /// &lt;summary&gt;
        /// Indicates a service-type logon. The account provided must have the service privilege enabled.
        /// &lt;/summary&gt;
        LOGON32_LOGON_SERVICE = 5,

        /// &lt;summary&gt;
        /// This logon type is for GINA DLLs that log on users who will be interactively using the computer.
        /// This logon type can generate a unique audit record that shows when the workstation was unlocked.
        /// &lt;/summary&gt;
        LOGON32_LOGON_UNLOCK = 7,

        /// &lt;summary&gt;
        /// This logon type preserves the name and password in the authentication package, which allows the server to make
        /// connections to other network servers while impersonating the client. A server can accept plaintext credentials
        /// from a client, call LogonUser, verify that the user can access the system across the network, and still
        /// communicate with other servers.
        /// NOTE: Windows NT:  This value is not supported.
        /// &lt;/summary&gt;
        LOGON32_LOGON_NETWORK_CLEARTEXT = 8,

        /// &lt;summary&gt;
        /// This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
        /// The new logon session has the same local identifier but uses different credentials for other network connections.
        /// NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
        /// NOTE: Windows NT:  This value is not supported.
        /// &lt;/summary&gt;
        LOGON32_LOGON_NEW_CREDENTIALS = 9,
    }
    public enum LogonProvider
    {
        /// &lt;summary&gt;
        /// Use the standard logon provider for the system.
        /// The default security provider is negotiate, unless you pass NULL for the domain name and the user name
        /// is not in UPN format. In this case, the default provider is NTLM.
        /// NOTE: Windows 2000/NT:   The default security provider is NTLM.
        /// &lt;/summary&gt;
        LOGON32_PROVIDER_DEFAULT = 0,
    }
    #endregion enums

    [DllImport("advapi32.dll", SetLastError = true)]
    //http://msdn.microsoft.com/en-us/library/aa378184(VS.85).aspx
    static extern bool LogonUser(string lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
    void Impersonate(string account)
    {
        Impersonate(account, GetPassword(account));
    }
    void Impersonate(string account, string pass)
    {
        string[] accountSplit = SplitAccount(account);
        Impersonate(accountSplit[0], accountSplit[1], pass);
    }
    void Impersonate(string domain, string user, string pass)
    {
        //thanks to http://www.codeproject.com/Messages/3656550/Re-Impersonation-using-Csharp.aspx
        IntPtr token;
        AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
        if (LogonUser(user, domain, pass, (int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS, (int)LogonProvider.LOGON32_PROVIDER_DEFAULT, out token))
        {
            WindowsIdentity fromIdentity = new WindowsIdentity(token);
            this.context = fromIdentity.Impersonate();
        }
        else
        {
            throw new NotImplementedException("Logon Issue"); //todo: create custom exception for this
        }
    }
    #endregion windows api reference

    #region fields
    const string DOMAIN_USER_SEPARATOR = @"\";
    WindowsImpersonationContext context;
    #endregion fields

    #region constructor
    public Impersonator(string account)
    {
        Impersonate(account);
    }
    public Impersonator(string account, string pass)
    {
        Impersonate(account, pass);
    }
    public Impersonator(string domain, string user, string pass)
    {
        Impersonate(domain, user, pass);
    }
    #endregion constructor

    #region helper methods
    string GetPassword(string account)
    {
        string[] accountSplit = SplitAccount(account);
        return GetPassword(accountSplit[0], accountSplit[1]);
    }
    string GetPassword(string domain, string user)
    {
        string pass = string.Empty;
        pass = "todo"; //todo:add code here to return the password for the given user from the secure store.
        return pass;
    }
    string[] SplitAccount (string account)
    {
        string[] accountSplit = account.Split(DOMAIN_USER_SEPARATOR.ToCharArray(), 2);
        return accountSplit;
    }
    #endregion helper methods

    #region disposal pattern
    private bool disposed = false;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // Free managed objects
            }
            // Free unmanaged objects
            this.context.Undo();
            this.context.Dispose();
            disposed = true;
        }
    }
    ~Impersonator()
    {
        Dispose (false);
    }
    #endregion disposal pattern

}


Thanks again,

JB
GeneralRe: Impersonation using C# Pin
Manfred Rudolf Bihy12-Nov-10 2:07
professionalManfred Rudolf Bihy12-Nov-10 2:07 
QuestionServer based on AsyncCallback not running as expected Pin
Tichaona J4-Nov-10 1:08
Tichaona J4-Nov-10 1:08 
AnswerRe: Server based on AsyncCallback not running as expected Pin
jschell4-Nov-10 8:32
jschell4-Nov-10 8:32 
QuestionGot a working ICMP listener; but how does it work? Pin
nebbukadnezzar4-Nov-10 0:28
nebbukadnezzar4-Nov-10 0:28 
QuestionRetrieve Value from TextBox Which is created in the code behind Pin
HatakeKaKaShi3-Nov-10 22:54
HatakeKaKaShi3-Nov-10 22:54 
AnswerRe: Retrieve Value from TextBox Which is created in the code behind Pin
John Gathogo4-Nov-10 1:00
John Gathogo4-Nov-10 1:00 
AnswerRe: Retrieve Value from TextBox Which is created in the code behind Pin
alrosan4-Nov-10 8:05
alrosan4-Nov-10 8:05 
Questionhow to find toolstrip button on a form by name Pin
Tridip Bhattacharjee3-Nov-10 21:27
professionalTridip Bhattacharjee3-Nov-10 21:27 
AnswerRe: how to find toolstrip button on a form by name [modified] Pin
Eddy Vluggen3-Nov-10 22:30
professionalEddy Vluggen3-Nov-10 22:30 
AnswerRe: how to find toolstrip button on a form by name Pin
_Erik_4-Nov-10 5:47
_Erik_4-Nov-10 5:47 
QuestionAdd Custom Utility Toolbar To VS2010 Pin
Kevin Marois3-Nov-10 12:52
professionalKevin Marois3-Nov-10 12:52 
AnswerRe: Add Custom Utility Toolbar To VS2010 Pin
Henry Minute3-Nov-10 12:56
Henry Minute3-Nov-10 12:56 
Questiondebugging mode behaves differently than final build Pin
kruegs353-Nov-10 6:02
kruegs353-Nov-10 6:02 
AnswerRe: debugging mode behaves differently than final build Pin
_Erik_3-Nov-10 6:14
_Erik_3-Nov-10 6:14 
GeneralRe: debugging mode behaves differently than final build Pin
kruegs353-Nov-10 6:41
kruegs353-Nov-10 6:41 
GeneralRe: debugging mode behaves differently than final build Pin
_Erik_3-Nov-10 6:49
_Erik_3-Nov-10 6:49 
AnswerRe: debugging mode behaves differently than final build Pin
Eddy Vluggen3-Nov-10 22:35
professionalEddy Vluggen3-Nov-10 22:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.