今天在討論區看到這樣的問題
有時利用ASP.NET執行時,會遇到權限不足的問題
所以必需提高權限才能執行某些程式
小朱大大提供了一個不錯的參考網址
小弟就用一的實例教大家如何實現這個功能
ASP.NET(C#)
HighLevelUser.aspx
01 |
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="HighLevelUser.aspx.cs" Inherits="HighLevelUser" %> |
07 |
<title>HighLevelUser</title> |
10 |
<form id="form1" runat="server"> |
HighLevelUser.aspx.cs
003 |
using System.Configuration; |
004 |
using System.Collections; |
006 |
using System.Web.Security; |
008 |
using System.Web.UI.WebControls; |
009 |
using System.Web.UI.WebControls.WebParts; |
010 |
using System.Web.UI.HtmlControls; |
011 |
using System.Runtime.InteropServices; |
012 |
using System.Security.Principal; |
015 |
public partial class HighLevelUser : System.Web.UI.Page |
018 |
public const int LOGON32_LOGON_INTERACTIVE = 2; |
019 |
public const int LOGON32_PROVIDER_DEFAULT = 0; |
021 |
WindowsImpersonationContext impersonationContext; |
023 |
[DllImport("advapi32.dll")] |
024 |
public static extern int LogonUserA(String lpszUserName, |
030 |
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] |
031 |
public static extern int DuplicateToken(IntPtr hToken, |
032 |
int impersonationLevel, |
033 |
ref IntPtr hNewToken); |
035 |
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] |
036 |
public static extern bool RevertToSelf(); |
038 |
[DllImport("kernel32.dll", CharSet = CharSet.Auto)] |
039 |
public static extern bool CloseHandle(IntPtr handle); |
041 |
public void Page_Load(Object s, EventArgs e) |
047 |
if (impersonateValidUser("Administrator", "localhost", "123456")) |
049 |
Response.Write(string.Format("驗證成功,目前使用者:{0}<br/>", WindowsIdentity.GetCurrent().Name)); |
052 |
File.AppendAllText(@"e:\log.txt", "F6 Team"); |
057 |
Response.Write(string.Format("作業完成,目前使用者:{0}<br/>", WindowsIdentity.GetCurrent().Name)); |
061 |
Response.Write(string.Format("驗證失敗,目前使用者:{0}<br/>", WindowsIdentity.GetCurrent().Name)); |
065 |
private bool impersonateValidUser(String userName, String domain, String password) |
067 |
WindowsIdentity tempWindowsIdentity; |
068 |
IntPtr token = IntPtr.Zero; |
069 |
IntPtr tokenDuplicate = IntPtr.Zero; |
073 |
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, |
074 |
LOGON32_PROVIDER_DEFAULT, ref token) != 0) |
076 |
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) |
078 |
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); |
079 |
impersonationContext = tempWindowsIdentity.Impersonate(); |
080 |
if (impersonationContext != null) |
083 |
CloseHandle(tokenDuplicate); |
089 |
if (token != IntPtr.Zero) |
091 |
if (tokenDuplicate != IntPtr.Zero) |
092 |
CloseHandle(tokenDuplicate); |
096 |
private void undoImpersonation() |
098 |
impersonationContext.Undo(); |
執行結果:
沒有權限的結果

有權限的結果

參考網址:
http://www.blueshop.com.tw/board/show.asp?subcde=BRD20090224193357J4D&fumcde=FUM20041006161839LRJ
http://support.microsoft.com/default.aspx/kb/306158
推到 Twitter!