Мне нужно было получить файл в веб-приложении и загрузить его в общую папку, требующую аутентификации. Этот класс работал довольно хорошо.

ел бы выдать себя за конкретного пользователя в коде, чтобы выполнить некоторые манипуляции с файлами на удаленной машине. Проблема в том, что я не могу заставить себя работать. Я использую код из статьи Microsoft, найденной здесь:Как реализовать олицетворение в приложении ASP.NET

Я хотел бы узнать, как и где начать процесс отладки. Вот мои файлы:

Test.aspx:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Test.aspx.vb" Inherits="TraceFile_Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    This is the test page!<br />
    <br />
    Result: <asp:Label ID="lblResult" runat="server"></asp:Label><br />
    <br />
    <asp:Button ID="btnRunTest" Text="Run Test" runat="server" />
    </div>
    </form>
</body>
</html>

Test.aspx.vb:

Imports System.Web
Imports System.Web.Security
Imports System.Security.Principal
Imports System.Runtime.InteropServices

Partial Class TraceFile_Test
    Inherits System.Web.UI.Page


    Dim LOGON32_LOGON_INTERACTIVE As Integer = 2
    Dim LOGON32_PROVIDER_DEFAULT As Integer = 0

    Dim impersonationContext As WindowsImpersonationContext

    Declare Function LogonUserA Lib "advapi32.dll" (ByVal lpszUsername As String, _
                            ByVal lpszDomain As String, _
                            ByVal lpszPassword As String, _
                            ByVal dwLogonType As Integer, _
                            ByVal dwLogonProvider As Integer, _
                            ByRef phToken As IntPtr) As Integer

    Declare Auto Function DuplicateToken Lib "advapi32.dll" ( _
                            ByVal ExistingTokenHandle As IntPtr, _
                            ByVal ImpersonationLevel As Integer, _
                            ByRef DuplicateTokenHandle As IntPtr) As Integer

    Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
    Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Long


    Public Sub Page_Load(ByVal s As Object, ByVal e As EventArgs)
        lblResult.Text = "Hit button to run test, please."
    End Sub

    Private Function impersonateValidUser(ByVal userName As String, _
    ByVal domain As String, ByVal password As String) As Boolean

        Dim tempWindowsIdentity As WindowsIdentity
        Dim token As IntPtr = IntPtr.Zero
        Dim tokenDuplicate As IntPtr = IntPtr.Zero
        impersonateValidUser = False

        If RevertToSelf() Then
            If LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, token) <> 0 Then
                If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then
                    tempWindowsIdentity = New WindowsIdentity(tokenDuplicate)
                    impersonationContext = tempWindowsIdentity.Impersonate()
                    If Not impersonationContext Is Nothing Then
                        impersonateValidUser = True
                    End If
                End If
            End If
        End If
        If Not tokenDuplicate.Equals(IntPtr.Zero) Then
            CloseHandle(tokenDuplicate)
        End If
        If Not token.Equals(IntPtr.Zero) Then
            CloseHandle(token)
        End If
    End Function

    Private Sub undoImpersonation()
        impersonationContext.Undo()
    End Sub


    Protected Sub btnRunTest_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRunTest.Click
        If impersonateValidUser("myUserName", "myDomain", "myPassword") Then
            'Insert your code that runs under the security context of a specific user here.
            Trace.Write("impersonation successful!")
            lblResult.Text = "success"
            undoImpersonation()
        Else
            'Your impersonation failed. Therefore, include a fail-safe mechanism here.
            Trace.Write("impersonation failed!")
            lblResult.Text = "fail"
        End If
    End Sub
End Class

Я заменил настоящие учетные данные myUserName, myDomain и myPassword для поста.

Веб-сервер - это сервер Windows 2008, работающий под управлением IIS 7. Я не являюсь сервером, поэтому я не знаю, где находится процесс устранения неполадок. Проблема с кодом или со стороны сервера?

Как всегда, заранее спасибо, что нашли время помочь!

Ответы на вопрос(0)

Ваш ответ на вопрос