C# 需要模拟用户访问网络资源,Asp.Net 账号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/233490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:12:44  来源:igfitidea点击:

Need to Impersonate user forAccessing Network resource, Asp.Net Account

c#.netasp.netimpersonationdelegation

提问by SharePoint Newbie

I need to access a network resource on which only a given Domain Account has access. I am using the LogonUser call, but get a "User does not have required priviliege" exception, as the web application is running with the asp.net account and it does not have adequate permissions to make this call.

我需要访问只有给定域帐户才能访问的网络资源。我正在使用 LogonUser 调用,但收到“用户不需要特权”异常,因为 Web 应用程序正在使用 asp.net 帐户运行,并且它没有足够的权限进行此调用。

Is there a way to get around it? Changing the identity or permissions of the ASP.Net account is not an option as this is a production machine with many projects running. Is there a better way to achieve this?

有没有办法绕过它?更改 ASP.Net 帐户的身份或权限不是一种选择,因为这是一台运行着许多项目的生产机器。有没有更好的方法来实现这一目标?

Using Asp.Net 2.0, Forms Authentication.

使用 Asp.Net 2.0,表单身份验证。

Kind Regards.

亲切的问候。

采纳答案by Michael L Perry

Just calling LogonUser is not enough. You need to impersonate that user. You can impersonate for just the access to the network resource.

仅调用 LogonUser 是不够的。您需要模拟该用户。您可以仅模拟访问网络资源。

Sample code can be found on MSDN.

示例代码可以在MSDN上找到。

回答by Eoin Campbell

You could add an

你可以添加一个

<identity impersonate="true" userName=""/>

tag to your web.config but that might not be ideal as you probably don't want to run the entire site as that user...

标记到您的 web.config 但这可能并不理想,因为您可能不想以该用户身份运行整个站点...

Can you map the network share as a local drive with the DomainName & Password... and then pull files to the website via the mapped drive ?

您可以使用域名和密码将网络共享映射为本地驱动器...然后通过映射的驱动器将文件拉到网站吗?

NET USE Z: \SERVER\Share password /USER:DOMAIN\Username /PERSISTENT:YES

回答by Dan F

I've only had intimate experience with this under 1.1, so things might hav changed in the 2.0 days but... We've got an app that gets deployed in intranet scenarios, and we strike the same thing. We run with identity impersonate turned on, forms mode authentication, anonymous access turned off. The easiest way to control this (that I've found) is to put the credentials of the user that has access in the web.config. They go on the node where you turn identity impersonate on. If it's super scret info I wouldn't do it this way though! We're only accessing shared graphics in a print environment, so most sites are happy to setup a limited account for us to put in the web.confit. LogonUser does indeed need elevated privelidges. Msdn has some good articles on how to impersonate a specific user in code. I'd fish out some links but this phone doesn't do copy paste.

我只在 1.1 下有过这方面的亲密体验,所以事情可能在 2.0 天内发生了变化,但是......我们有一个应用程序部署在 Intranet 场景中,我们遇到了同样的事情。我们在打开身份模拟、表单模式身份验证、关闭匿名访问的情况下运行。控制这个(我发现的)最简单的方法是将具有访问权限的用户的凭据放在 web.config 中。他们进入您打开身份模拟的节点。如果是超级秘密信息,我不会这样做!我们只在打印环境中访问共享图形,因此大多数站点都乐于为我们设置一个有限的帐户以将其放入 web.confit。LogonUser 确实需要提升权限。msdn 有一些关于如何在代码中模拟特定用户的好文章。一世'

回答by Howard Pinsley

Can you change the ACL protecting the network resource? A trick I've used in the past is to create an Active Directory group and then put the Computer Object into that group. I then use that group in the Access Control List of the object (file, share, etc) that I need to access.

你能改变保护网络资源的ACL吗?我过去使用的一个技巧是创建一个 Active Directory 组,然后将计算机对象放入该组中。然后,我在需要访问的对象(文件、共享等)的访问控制列表中使用该组。

This has allowed me to run Windows Services as Local System and get access to the protected network resources. And this trick also seems to work for the ASP.NET process which runs as Network Service.

这使我能够将 Windows 服务作为本地系统运行并访问受保护的网络资源。这个技巧似乎也适用于作为网络服务运行的 ASP.NET 进程。

回答by Howard Pinsley

  • With this WebPart y connect to a net resource with restricted access I put a file and y close the connection with the resource (as user with granted access), you dont need to make a new share connection, that was de only restricction, that my sistems departament make to me. May be, there are many imports that necesary, but I do to many tests and I havent got time to clean the code. I hope that help to you. (sorry for my poor english).
  • 使用此 WebPart 连接到具有受限访问权限的网络资源我放置一个文件并关闭与资源的连接(作为具有授予访问权限的用户),您不需要建立新的共享连接,这只是限制,我的系统部门给我做的。可能有很多导入是必要的,但我做了很多测试,我没有时间清理代码。我希望对你有帮助。(对不起,我的英语不好)。

Imports System Imports System.ComponentModel Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.IO Imports System.IO.File Imports System.Diagnostics Imports System.Xml.Serialization Imports Microsoft.SharePoint Imports Microsoft.SharePoint.Utilities Imports Microsoft.SharePoint.WebPartPages Imports Microsoft.SharePoint.WebControls Imports Microsoft.SharePoint.Administration Imports System.Security.Principal Imports System.Security.Permissions Imports System.Runtime.InteropServices Imports System.Environment Imports System.Net.Sockets Imports System.Web.UI.HtmlControls

导入 System.ComponentModel 导入 System.Web.UI 导入 System.Web.UI.WebControls 导入 System.IO 导入 System.IO.File 导入 System.Diagnostics 导入 System.Xml.Serialization 导入 Microsoft.SharePoint 导入 Microsoft.SharePoint.Utilities导入 Microsoft.SharePoint.WebPartPages 导入 Microsoft.SharePoint.WebControls 导入 Microsoft.SharePoint.Administration 导入 System.Security.Principal 导入 System.Security.Permissions 导入 System.Runtime.InteropServices 导入 System.Environment 导入 System.Net.Sockets 导入 System.Web .UI.HtmlControls

Public Class Impersonalizacion Private Const LOGON32_PROVIDER_DEFAULT As Integer = 0 Private Const LOGON32_LOGON_INTERACTIVE As Integer = 2

公共类非个性化 Private Const LOGON32_PROVIDER_DEFAULT As Integer = 0 Private Const LOGON32_LOGON_INTERACTIVE As Integer = 2

<DllImport("advapi32.dll", SetLastError:=True)> _
Public 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 IntPtr) As Boolean
End Function

<DllImport("advapi32.dll", EntryPoint:="DuplicateToken", ExactSpelling:=False, CharSet:=CharSet.Auto, SetLastError:=True)> _
Public Shared Function DuplicateToken(ByVal ExistingTokenHandle As IntPtr, ByVal ImpersonationLevel As Integer, ByRef DuplicateTokenHandle As IntPtr) As Integer
End Function

Public Shared Function WinLogOn(ByVal strUsuario As String, ByVal strClave As String, ByVal strDominio As String) As WindowsImpersonationContext
    Dim tokenDuplicate As New IntPtr(0)
    Dim tokenHandle As New IntPtr(0)
    If LogonUser(strUsuario, strDominio, strClave, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, tokenHandle) Then
        If DuplicateToken(tokenHandle, 2, tokenDuplicate) <> 0 Then
            Return (New WindowsIdentity(tokenDuplicate)).Impersonate()
        End If
    End If
    Return Nothing
End Function

End Class 'Description for WebPart1. "), XmlRoot(Namespace:="SPSCopiarFichero")> _ Public Class WebPart1 Inherits Microsoft.SharePoint.WebPartPages.WebPart

End Class 'WebPart1 的描述。"), XmlRoot(Namespace:="SPSCopiarFichero")> _ Public Class WebPart1 继承 Microsoft.SharePoint.WebPartPages.WebPart

Protected WithEvents File1 As HtmlInputFile

Dim vdestino As String = "\centappd20nd01\uploads_avisos"
Dim vtemporal As String = "c:\pdf"

Protected WithEvents boton1 As Button
Protected WithEvents usuario As TextBox
Protected WithEvents contra As TextBox
Protected WithEvents dominio As TextBox
Protected WithEvents destino As TextBox
Protected WithEvents origen As TextBox
Protected WithEvents temporal As TextBox
Protected WithEvents log As TextBox
'Render this Web Part to the output parameter specified.
Protected Overrides Sub RenderWebPart(ByVal output As System.Web.UI.HtmlTextWriter)
    log.RenderControl(output)
    output.Write("<br><font>Ruta Origen</font><br>")
    File1.RenderControl(output)
    output.Write("<br><font>Ruta Temporal </font><br>")
    temporal.RenderControl(output)
    output.Write("<br><font>Ruta Destino </font><br>")
    destino.RenderControl(output)
    output.Write("<br><font>Usuario </font><br>")
    usuario.RenderControl(output)
    output.Write("<br><font>Contrase?a </font><br>")
    contra.RenderControl(output)
    output.Write("<br><font>Dominio </font><br>")
    dominio.RenderControl(output)
    output.Write("<br><br><center>")
    boton1.RenderControl(output)
    output.Write("</center>")
End Sub
Protected Overrides Sub CreateChildControls()

    dominio = New TextBox
    With dominio
        .Text = "admon-cfnavarra"
        .Width = Unit.Pixel("255")
    End With
    Controls.Add(dominio)

    boton1 = New Button
    With boton1
        .Text = "Copiar Fichero"
    End With
    Controls.Add(boton1)

    File1 = New HtmlInputFile
    With File1

    End With
    Controls.Add(File1)

    usuario = New TextBox
    With usuario
        .Text = "SVCWSINCPre_SNS"
        .Width = Unit.Pixel("255")
    End With
    Controls.Add(usuario)

    contra = New TextBox
    With contra
        .Text = "SVCWSINCPre_SNS"
        .Width = Unit.Pixel("255")
    End With
    Controls.Add(contra)

    destino = New TextBox
    With destino
        .Text = vdestino
        .Width = Unit.Pixel("255")
    End With
    Controls.Add(destino)

    log = New TextBox
    With log
        .Width = Unit.Percentage(100)
        .BackColor = System.Drawing.Color.Black
        .ForeColor = System.Drawing.Color.White
    End With
    Controls.Add(log)

    temporal = New TextBox
    With temporal
        .Text = vtemporal
        .Width = Unit.Pixel("255")
    End With
    Controls.Add(temporal)
End Sub
Private Sub boton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles boton1.Click
    If File1.PostedFile.FileName <> "" Then
        Dim _objContext As WindowsImpersonationContext = Nothing
        log.Text = QuienSoy()
        CopyFile(File1.PostedFile.FileName, temporal.Text)
        _objContext = Impersonalizacion.WinLogOn(usuario.Text, contra.Text, dominio.Text)
        CopyFile(temporal.Text & "\" & System.IO.Path.GetFileName(File1.PostedFile.FileName), destino.Text)
        _objContext.Undo()
    Else
        log.Text = "Se debe introducir un fichero"
    End If
End Sub
Friend Shared Function QuienSoy() As String
    Return WindowsIdentity.GetCurrent().Name
End Function
Public Function CopyFile(ByVal StartPath As String, ByVal EndPath As String)
    Try
        Dim fn As String = System.IO.Path.GetFileName(StartPath)
        System.IO.File.Copy(StartPath, EndPath & "\" & fn, False)
        log.Text = "Fichero Copiado Correctamente"
    Catch ex As Exception
        log.Text = ex.Message
    End Try
End Function

End Class

结束类