[轉載]Run As Administrator

[本文轉自博客堂]
在Windows Vista运行Visual Studio 2005(without SP1)时,最好使用Vista的Run as administrator的功能,否则有些功能就不能正常工作。而在我们开发的.NET程序内部,有时也会碰到需要临时提高权限的情形。ASP.NET程序员经常问的一个问题是,我的代码为什么没有权限创建一个文件?基本的解决方案有三个:

  • 提升ASPNET帐户(在Windows 2003则是Network Service)的权限(不推荐)
  • 为目标文件或文件夹设置ASPNET帐户的读写权限(如果需要访问的文件路径是固定的)
  • 在web.config设置impersonate,以另一个帐户的身份运行程序,比如Administrator...

论坛和新闻组里面常出现的另一个问题是,如何访问网上邻居或者映射的网络驱动器?常见的答案是使用Process.Start方法调用cmd.exe执行一个net use命令,这个方案是可行的但是显然不科学... 这里同样是权限问题。

.NET类库自带了个WindowsImpersonationContext类,可以用来进行用户身份模拟。不过创建这个对象的唯一办法调用WindowsIdentity.Impersonate(IntPtr userToken)方法,而userToken却只有通过Windows API调用而来(根本就是没打算让人用的)... MSDN上语焉不详,而实际上Windows SDK解释的更清楚,在LogonUser页有完整的说明和示例。于是使用P/Invoke封装了LogonUser、ImpersonateLoggedOnUser、RevertToSelf这几个API以及相关的一些枚举类,实现了一个IdentityScope类。演示代码:
Console.WriteLine(WindowsIdentity.GetCurrent().Name);
using (new IdentityScope("SUMA-LP", "Administrator", "********"))
{
    Console.WriteLine(WindowsIdentity.GetCurrent().Name);
}
Console.WriteLine(WindowsIdentity.GetCurrent().Name);

Console将输出:
Redmond\V-Wexia
SUMA-LP\Administrator
Redmond\V-Wexia

你可以看到在这个using代码块里面执行者身份成功的扮演了本机的Administrator。在访问网上共享资源的时候这个类同样有效,比如:
using (new IdentityScope("Domain", "User", "Password", LogonType.NewCredentials, LogonProvider.WinNT50))
{
    File.Copy("file.ext", "\\shared\folder\file.ext");
}

这里使用LogonType.NewCredentials登陆类型意味着本地身份不变,访问网络资源时使用扮演的身份。


  1namespace Sunmast.SharedCode
  2{
  3    /// <summary>
  4    /// The type of logon operation to perform.
  5    /// </summary>

  6    enum LogonType : uint
  7    {
  8        /// <summary>
  9        /// 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.
 10        /// </summary>

 11        Interactive = 2,
 12        /// <summary>
 13        /// This logon type is intended for high performance servers to authenticate plaintext passwords. The LogonUser function does not cache credentials for this logon type.
 14        /// </summary>

 15        Network = 3,
 16        /// <summary>
 17        /// 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.
 18        /// </summary>

 19        Batch = 4,
 20        /// <summary>
 21        /// Indicates a service-type logon. The account provided must have the service privilege enabled.
 22        /// </summary>

 23        Service = 5,
 24        /// <summary>
 25        /// 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.
 26        /// </summary>

 27        Unlock = 7,
 28        /// <summary>
 29        /// 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.
 30        /// </summary>

 31        NetworkClearText = 8,
 32        /// <summary>
 33        /// 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.<br/>
 34        /// This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
 35        /// </summary>

 36        NewCredentials = 9
 37    }

 38
 39    /// <summary>
 40    /// Specifies the logon provider.
 41    /// </summary>

 42    enum LogonProvider : uint
 43    {
 44        /// <summary>
 45        /// Use the standard logon provider for the system.<br/>
 46        /// 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.
 47        /// </summary>

 48        Default = 0,
 49        /// <summary>
 50        /// Use the Windows NT 3.5 logon provider.
 51        /// </summary>

 52        WinNT35 = 1,
 53        /// <summary>
 54        /// Use the NTLM logon provider.
 55        /// </summary>

 56        WinNT40 = 2,
 57        /// <summary>
 58        /// Use the negotiate logon provider.
 59        /// </summary>

 60        WinNT50 = 3,
 61    }

 62
 63    /// <summary>
 64    /// Use identity scope to impersonate a different user
 65    /// </summary>

 66    class IdentityScope : IDisposable
 67    {
 68        [DllImport("Advapi32.dll")]
 69        static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword,
 70            LogonType dwLogonType, LogonProvider dwLogonProvider, out IntPtr phToken);
 71        [DllImport("Advapi32.DLL")]
 72        static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
 73        [DllImport("Advapi32.DLL")]
 74        static extern bool RevertToSelf();
 75        [DllImport("Kernel32.dll")]
 76        static extern int GetLastError();
 77
 78        bool disposed;
 79
 80        public IdentityScope(string domain, string userName, string password)
 81            : this(domain, userName, password, LogonType.Interactive, LogonProvider.Default)
 82        {
 83        }

 84
 85        public IdentityScope(string domain, string userName, string password, LogonType logonType, LogonProvider logonProvider)
 86        {
 87            if (string.IsNullOrEmpty(userName))
 88            {
 89                throw new ArgumentNullException("userName");
 90            }

 91            if (string.IsNullOrEmpty(domain))
 92            {
 93                domain = ".";
 94            }

 95
 96            IntPtr token;
 97            int errorCode = 0;
 98            if (LogonUser(userName, domain, password, logonType, logonProvider, out token))
 99            {
100                if (!ImpersonateLoggedOnUser(token))
101                {
102                    errorCode = GetLastError(); 
103                }

104            }

105            else
106            {
107                errorCode = GetLastError();
108            }

109            if (errorCode != 0)
110            {
111                throw new Win32Exception(errorCode);
112            }

113        }

114
115        ~IdentityScope()
116        {
117            Dispose(false);
118        }

119
120        protected virtual void Dispose(bool disposing)
121        {
122            if (!disposed)
123            {
124                if (disposing)
125                {
126                    // Nothing to do.
127                }

128                RevertToSelf();
129                disposed = true;
130            }

131        }

132
133        public void Dispose()
134        {
135            Dispose(true);
136            GC.SuppressFinalize(this);
137        }

138    }

139}
posted @ 2007-01-03 16:54  萍踪侠影  阅读(1695)  评论(0编辑  收藏  举报