我正在计算机上运行进程。我想从这台机器连接,即通过Windows身份验证连接到SQL Server。无法授予该计算机对此服务器的访问权限。仅授予特定的非个人帐户访问权限。
我可以使用WindowsImpersonationContext模拟NPA帐户。在这种情况下,在NPA下,我可以轻松地通过Windows身份验证连接到SQL数据库。但是在这一点上,代码无法与计算机上的任何文件一起使用。访问被拒绝。 请参阅下面的代码(可在互联网上找到)进行模拟。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using System.Security.Permissions;
using System.ComponentModel;
using System.Runtime.ConstrainedExecution;
using Microsoft.Win32.SafeHandles;
namespace WindowsImpersonation {
public class WrapperImpersonationContext {
[DllImport( "advapi32.dll", SetLastError = true )]
public static extern bool LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
out IntPtr phToken
);
[DllImport( "kernel32.dll", SetLastError = true )]
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs( UnmanagedType.Bool )]
static extern bool CloseHandle( IntPtr hObject );
private const int LOGON32_PROVIDER_DEFAULT = 0;
private const int LOGON32_LOGON_INTERACTIVE = 2;
private string m_Domain;
private string m_Password;
private string m_Username;
private IntPtr m_Token;
private WindowsImpersonationContext m_Context = null;
protected bool IsInContext {
get { return m_Context != null; }
}
public WrapperImpersonationContext( string domain, string username, string password ) {
m_Domain = domain;
m_Username = username;
m_Password = password;
}
[PermissionSet( SecurityAction.Demand, Name = "FullTrust" )]
public void Enter() {
if ( this.IsInContext ) return;
m_Token = new IntPtr( 0 );
try {
m_Token = IntPtr.Zero;
bool logonSuccessfull = LogonUser(
m_Username,
m_Domain,
m_Password,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
out m_Token );
if ( logonSuccessfull == false ) {
int error = Marshal.GetLastWin32Error();
throw new Win32Exception( error );
}
WindowsIdentity identity = new WindowsIdentity( m_Token );
m_Context = identity.Impersonate();
}
catch ( Exception exception ) {
Console.WriteLine( "exception catched: " + exception.Message.ToString() );
}
}
[PermissionSet( SecurityAction.Demand, Name = "FullTrust" )]
public void Leave() {
if ( this.IsInContext == false ) return;
m_Context.Undo();
if ( m_Token != IntPtr.Zero ) CloseHandle( m_Token );
m_Context = null;
}
}
}
在输入模拟的同时,还可以给我一个正在模拟的帐户授予在运行代码的计算机上使用文件的权限吗?