[轉載]Run As Administrator

本文介绍了解决.NET程序中权限不足的问题,提供了三种基本解决方案,并深入探讨了如何使用WindowsImpersonationContext类来模拟不同用户身份,以解决访问限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[本文轉自博客堂]
在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登陆类型意味着本地身份不变,访问网络资源时使用扮演的身份。


  1None.gifnamespace Sunmast.SharedCode
  2ExpandedBlockStart.gifContractedBlock.gifdot.gif{
  3ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
  4InBlock.gif    /// The type of logon operation to perform.
  5ExpandedSubBlockEnd.gif    /// </summary>

  6InBlock.gif    enum LogonType : uint
  7ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
  8ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
  9InBlock.gif        /// 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.
 10ExpandedSubBlockEnd.gif        /// </summary>

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

 15InBlock.gif        Network = 3,
 16ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 17InBlock.gif        /// 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.
 18ExpandedSubBlockEnd.gif        /// </summary>

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

 23InBlock.gif        Service = 5,
 24ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 25InBlock.gif        /// 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.
 26ExpandedSubBlockEnd.gif        /// </summary>

 27InBlock.gif        Unlock = 7,
 28ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 29InBlock.gif        /// 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.
 30ExpandedSubBlockEnd.gif        /// </summary>

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

 36InBlock.gif        NewCredentials = 9
 37ExpandedSubBlockEnd.gif    }

 38InBlock.gif
 39ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
 40InBlock.gif    /// Specifies the logon provider.
 41ExpandedSubBlockEnd.gif    /// </summary>

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

 48InBlock.gif        Default = 0,
 49ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 50InBlock.gif        /// Use the Windows NT 3.5 logon provider.
 51ExpandedSubBlockEnd.gif        /// </summary>

 52InBlock.gif        WinNT35 = 1,
 53ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 54InBlock.gif        /// Use the NTLM logon provider.
 55ExpandedSubBlockEnd.gif        /// </summary>

 56InBlock.gif        WinNT40 = 2,
 57ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 58InBlock.gif        /// Use the negotiate logon provider.
 59ExpandedSubBlockEnd.gif        /// </summary>

 60InBlock.gif        WinNT50 = 3,
 61ExpandedSubBlockEnd.gif    }

 62InBlock.gif
 63ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
 64InBlock.gif    /// Use identity scope to impersonate a different user
 65ExpandedSubBlockEnd.gif    /// </summary>

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

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

 91InBlock.gif            if (string.IsNullOrEmpty(domain))
 92ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 93InBlock.gif                domain = ".";
 94ExpandedSubBlockEnd.gif            }

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

104ExpandedSubBlockEnd.gif            }

105InBlock.gif            else
106ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
107InBlock.gif                errorCode = GetLastError();
108ExpandedSubBlockEnd.gif            }

109InBlock.gif            if (errorCode != 0)
110ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
111InBlock.gif                throw new Win32Exception(errorCode);
112ExpandedSubBlockEnd.gif            }

113ExpandedSubBlockEnd.gif        }

114InBlock.gif
115InBlock.gif        ~IdentityScope()
116ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
117InBlock.gif            Dispose(false);
118ExpandedSubBlockEnd.gif        }

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

128InBlock.gif                RevertToSelf();
129InBlock.gif                disposed = true;
130ExpandedSubBlockEnd.gif            }

131ExpandedSubBlockEnd.gif        }

132InBlock.gif
133InBlock.gif        public void Dispose()
134ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
135InBlock.gif            Dispose(true);
136InBlock.gif            GC.SuppressFinalize(this);
137ExpandedSubBlockEnd.gif        }

138ExpandedSubBlockEnd.gif    }

139ExpandedBlockEnd.gif}

转载于:https://www.cnblogs.com/floatping/archive/2007/01/03/610676.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值