private enum EoleAuthenticationCapabilities
{
EOAC_NONE,
}
private enum AuthnLevel
{
RPC_C_AUTHN_LEVEL_DEFAULT,
RPC_C_AUTHN_LEVEL_NONE,
RPC_C_AUTHN_LEVEL_CONNECT,
RPC_C_AUTHN_LEVEL_CALL,
RPC_C_AUTHN_LEVEL_PKT,
RPC_C_AUTHN_LEVEL_PKT_INTEGRITY,
RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
}
private enum ImpLevel
{
RPC_C_IMP_LEVEL_DEFAULT,
RPC_C_IMP_LEVEL_ANONYMOUS,
RPC_C_IMP_LEVEL_IDENTIFY,
RPC_C_IMP_LEVEL_IMPERSONATE,
RPC_C_IMP_LEVEL_DELEGATE,
}
private struct CoAuthIdentity
{
[MarshalAs(UnmanagedType.LPWStr)]
public string User;
public uint UserLength;
[MarshalAs(UnmanagedType.LPWStr)]
public string Domain;
public uint DomainLength;
[MarshalAs(UnmanagedType.LPWStr)]
public string Password;
public uint PasswordLength;
public uint Flags;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct SoleAuthenticationList
{
public uint CAuthInfo;
public IntPtr AAuthInfo;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct SoleAuthenticationInfo
{
public int DwAuthnSvc;
public int DwAuthzSvc;
public IntPtr PAuthInfo;
}
[DllImport("ole32.dll")]
private static extern int CoInitializeSecurity(
IntPtr pSecDesc,
int cAuthSvc,
IntPtr asAuthSvc,
IntPtr pReserved1,
App.AuthnLevel dwAuthnLevel,
App.ImpLevel dwImpLevel,
IntPtr pAuthList,
App.EoleAuthenticationCapabilities dwCapabilities,
IntPtr pReserved3);
private static int InitializeSecurity()
{
App.CoAuthIdentity structure1 = new App.CoAuthIdentity();
IntPtr ptr1 = Marshal.AllocCoTaskMem(50);
structure1.User = "SecurityAdmin";
structure1.UserLength = (uint) structure1.User.Length;
structure1.Domain = ".";
structure1.DomainLength = (uint) structure1.Domain.Length;
structure1.Password = string.Empty;
structure1.PasswordLength = (uint) structure1.Password.Length;
structure1.Flags = 2U;
Marshal.StructureToPtr<App.CoAuthIdentity>(structure1, ptr1, false);
App.SoleAuthenticationInfo[] authenticationInfoArray = new App.SoleAuthenticationInfo[2];
authenticationInfoArray[0].DwAuthnSvc = 10;
authenticationInfoArray[0].DwAuthzSvc = 0;
authenticationInfoArray[0].PAuthInfo = ptr1;
authenticationInfoArray[1].DwAuthnSvc = 16;
authenticationInfoArray[1].DwAuthzSvc = 0;
authenticationInfoArray[1].PAuthInfo = ptr1;
GCHandle gcHandle = GCHandle.Alloc((object) authenticationInfoArray, GCHandleType.Pinned);
App.SoleAuthenticationList structure2 = new App.SoleAuthenticationList()
{
CAuthInfo = 2,
AAuthInfo = gcHandle.AddrOfPinnedObject()
};
IntPtr num1 = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof (App.SoleAuthenticationList)));
IntPtr ptr2 = num1;
Marshal.StructureToPtr<App.SoleAuthenticationList>(structure2, ptr2, false);
int num2 = App.CoInitializeSecurity(IntPtr.Zero, -1, IntPtr.Zero, IntPtr.Zero, App.AuthnLevel.RPC_C_AUTHN_LEVEL_DEFAULT, App.ImpLevel.RPC_C_IMP_LEVEL_IDENTIFY, num1, App.EoleAuthenticationCapabilities.EOAC_NONE, IntPtr.Zero);
gcHandle.Free();
Marshal.FreeCoTaskMem(ptr1);
Marshal.FreeCoTaskMem(num1);
return num2;
}
c# CoInitializeSecurityd调用方法
于 2025-07-08 09:53:21 首次发布