C# 尝试读取或写入受保护的内存。这通常指示其他内存已损坏

一般来说IIS的验证方式有好几种,比较常见的就是匿名验证,集成Windows验证等等。 但是集成Windows验证每次都会谈个对话框出来,很麻烦,特别是在使用代理的情况下。

于是想能不能用一种Form的方式实现Windows验证呢? 当然啦,想想而已,本来对WEB开发就不算熟, Windows方面的就更差了。

在网上搜索到了一种方式,利用 advapi32.dll的LogonUser方法是可以验证你输入的用户名密码是不是Windows的有效用户的。

代码如下 :

   'include permissions namespace for security attributes
   'include principal namespace for windowsidentity class
   'include interopservices namespace for dllImports.

   Imports System.Security.Principal
   Imports System.Security.Permissions
   Imports System.Runtime.InteropServices

   '<Assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode:=True)>
   Public Class LogInUser

    <DllImport("C://WINDOWS//System32//advapi32.dll")> _
    Private Shared Function LogonUser(ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal     

    lpszPassword As String, _    ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, ByRef phToken  As Integer) As Boolean
    End Function

    <DllImport("C://WINDOWS//System32//Kernel32.dll")> _
    Private Shared Function GetLastError() As Integer
    End Function

    Public Shared Function LogInThisUser(ByVal username As String, ByVal domainname As String, _
            ByVal password As String) As String

        Try
            'The Windows NT user token.
            Dim token1 As Integer

            'Get the user token for the specified user, machine, and password using the unmanaged LogonUser method.

            'The parameters for LogonUser are the user name, computer name, password,
            'Logon type (LOGON32_LOGON_NETWORK_CLEARTEXT), Logon provider (LOGON32_PROVIDER_DEFAULT),
            'and user token.
            Dim loggedOn As Boolean = LogonUser(username, domainname, password, 3, 0, token1)

            'impersonate user
            Dim token2 As IntPtr = New IntPtr(token1)
            Dim mWIC As WindowsImpersonationContext = _
                New WindowsIdentity(token2).Impersonate

        Catch e As Exception
            'error occurred.. error number unknown.
            Return "Err. occurred : " & e.Message
        End Try

        Dim winUser As WindowsIdentity
        Return winUser.GetCurrent.Name
    End Function

End Class

 

不过网上的VB代码,我习惯用的是C#,于是一行一行的转换。结果后来执行的时候就出错了: 提示 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。

开始以为是因为要获取系统用户信息,所以需要的权限比较高或者是会读去受保护的系统信息。 继续搜索这个错误,发现是因为使用了非托管代码,而且我转换LogonUser函数中的最后一个变量  ByRef phToken  As Integer时,转换成了INT,实际上应该是ref InPtr类型,因为引用非托管代码函数参数错误,所以报这个错误。

至于托管代码和非托管代码更详细的差别还得以后慢慢研究了。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值