How can I temporarily impersonate a user to open a file?

后端 未结 2 1415
梦谈多话
梦谈多话 2021-01-03 16:59

I would like to temporarily impersonate a domain user account to read in a file on a network drive from an ASP.NET site.

I would rather not set up impersonation for

2条回答
  •  长发绾君心
    2021-01-03 17:49

    Actually, the process is quite easy, you can use code like this;

    using System.Security.Principal;
    ...
    // Obtain the authenticated user's Identity
    WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
    WindowsImpersonationContext ctx = null;
    try
    {
      // Start impersonating
      ctx = winId.Impersonate();
      // Now impersonating
      // Access resources using the identity of the authenticated user
    }
    // Prevent exceptions from propagating
    catch
    {
    }
    finally
    {
      // Revert impersonation
      if (ctx != null)
        ctx.Undo();
    }
    // Back to running under the default ASP.NET process identity
    

    Your code goes in the "Now impersonating" section. the KEY is the finally block, this is VERY important. You can view this MSDN article for full details on how this works.

提交回复
热议问题