当前位置: 首页 > 编程语言 > C#

LogonUser和Delegate分享

时间:2023-04-10 20:47:53 C#

LogonUser和Delegate我正在使用LogonUserwin32api:token=LogonUser(...)WindowsImpersonationContextimpersonatedUser=newId.Impersonate();但是,在此之后调用WCF服务时,我无法使用模拟。我认为这是因为impersonatedUser.ImpersonationLevel等于模拟。是什么原因?ImpersonationLevel.Identification是我需要的级别吗?如何达到这样的水平?我不知道这是否适用于WCF。但我们在生产Web应用程序中使用它来模拟文件系统的读写文件。您需要为AdvApi32.LogonUser、AdvApi32.DuplicateToken和Kernel32.CloseHandle定义API,并确保在完成后关闭WindowsImpersonationContext。///模拟用户///用户帐户的域名///用户的密码///newWindowsImpersonationContextpublicstaticWindowsImpersonationContextImpersonateUser(Stringusername,Stringpassword){WindowsIdentitywinId=WindowsIdentity.GetCurrent();if(winId!=null){if(string.Compare(winId.Name,username,true)==0){返回null;}}//定义句柄IntPtrexistingTokenHandle=IntPtr.Zero;IntPtrduplicateTokenHandle=IntPtr.Zero;字符串域;if(username.IndexOf("\")>0){//拆分域和名称String[]splitUserName=username.Split('\');域=拆分用户名[0];用户名=拆分用户名[1];}else{域=String.Empty;}try{//获取安全令牌boolisOkay=AdvApi32.LogonUser(username,domain,password,(int)AdvApi32.LogonTypes.LOGON32_LOGON_INTERACTIVE,(int)AdvApi32.LogonTypes.LOGON32_PROVIDER_DEFAULT,refexistingTokenHandle);如果(!isOkay){intlastWin32Error=Marshal.GetLastWin32Er错误();intlastError=Kernel32.GetLastError();thrownewException("LogonUserFailed:"+lastWin32Error+"-"+lastError);}//复制令牌isOkay=AdvApi32.DuplicateToken(existingTokenHandle,(int)AdvApi32.SecurityImpersonationLevel.SecurityImpersonation,refduplicateTokenHandle);如果(!isOkay){intlastWin32Error=Marshal.GetLastWin32Error();intlastError=Kernel32.GetLastError();Kernel32.CloseHandle(existingTokenHandle);thrownewException("DuplicateTokenFailed:"+lastWin32Error+"-"+lastError);}//从令牌创建身份WindowsIdentitynewId=newWindowsIdentity(duplicateTokenHandle);WindowsImpersonationContextimpersonatedUser=newId.Impersonate();返回模拟用户;}finally{//释放所有句柄if(existingTokenHandle!=IntPtr.Zero){Kernel32.CloseHandle(existingTokenHandle);}if(duplicateTokenHandle!=IntPtr.Zero){Kernel32.CloseHandle(duplicateTokenHandle);}}}在此之后,我无法使用模拟角色模拟应该对在同一个盒子上访问有效,但在Web上无效正如consultutah的代码所建议的,它可能需要调用DuplicateToken()以便在使用之前将登录令牌转换为模拟令牌。我认为这是因为impersonatedUser.ImpersonationLevel等于模拟。如果您需要充当另一个系统的模拟用户,则需要更高级别的模拟,称为“委派”。这基本上等同于拥有用户的密码,因此您可以将自己表示为其他人。以上就是C#学习教程的全部内容:LogonUser和委托分享。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: