【问题标题】:ASP.NET Getting Current User NameASP.NET 获取当前用户名
【发布时间】:2011-07-07 18:59:44
【问题描述】:

我正在尝试使用 ASP.NET 和 VB.NET 在我们公司的 Intranet 上构建一个应用程序。

一旦我的应用程序发布到 IIS,这些函数都不会返回任何内容。它们在开发中运行良好(即:按 F5 我会得到我的常规网络用户名),但一旦发布它们就会返回 ''(一个空字符串)。

HttpContext.Current.User.Identity.Name
Page.User.Identity.Name

我正在寻找能够获取当前用户登录名的东西——任何东西。请注意,由于其他功能要求,我无法在 web.config 中更改这些设置。

    <authentication mode="Windows"/>

    <roleManager enabled="true" cacheRolesInCookie="true" defaultProvider="AspNetWindowsTokenRoleProvider" cookieName=".ASPXROLES" cookiePath="/" cookieTimeout="480" cookieRequireSSL="false" cookieSlidingExpiration="true" createPersistentCookie="false" cookieProtection="All" />

我也不能更改任何 IIS 设置,包括“启用匿名用户”设置。规格是一成不变的,我必须砍掉自己的腿(或头)才能更换。

我认为必须有一种方法可以使用我当前的配置获取当前登录用户的名称。

有什么想法吗?

谢谢,

杰森

【问题讨论】:

标签: asp.net iis intranet


【解决方案1】:

在 IIS 中禁用匿名身份验证。 如果在 IIS 中启用匿名身份验证,User.Identity.Name 可能为空。

在 web.config 中设置

<configuration>
  <system.web>
    <authentication mode="Windows" />
         <authorization>
             <deny users="?"/>
          </authorization> 
    </system.web> 
</configuration>

使用User.Identity.Name 获取登录用户。

Environment.UserName 是正在运行的线程标识。如果您按照 Mark 所说启用了 Impersonation,您会发现返回的结果会有所不同。但是,这需要 ASP.NET 模拟。如果您不需要 ASP.NET Impersonation 和处理线程标识,则可以忽略 Environment.UserName if 而只使用 User.Identity.Name.

在执行任何操作之前还要check

 if (User.Identity.IsAuthenticated)
    {
        Page.Title = "Home page for " + User.Identity.Name;
    }
    else
    {
        Page.Title = "Home page for guest user.";
    }

这是good example

【讨论】:

    【解决方案2】:

    我很确定让它工作的唯一方法是实际检查 IIS 中的“集成 Windows 身份验证”。如果还选中了“启用匿名访问”,它将只使用匿名,所以你应该关闭它...

    【讨论】:

    • 是否设置为“允许”?如果是这样,您可以将其添加到您的 web.config 中吗? &lt;authorization&gt; &lt;deny users="?" /&gt; &lt;/authorization&gt;
    【解决方案3】:

    这是我(在某处)找到并最终使用的。希望它可以帮助其他人!

    Public Shared Function Check_If_Member_Of_AD_Group(ByVal username As String, _
    ByVal grouptoCheck As String, _
    ByVal domain As String, _
    ByVal ADlogin As String, _
    ByVal ADpassword As String) _
    As Boolean
    
        Dim myDE As DirectoryEntry
        Dim EntryString As String
        Dim NumberOfGroups As Integer
        Dim tempString As String
    
    
        'Checks to see if the specified user is a member of the specified group
        Try
    
            'Setup the LDAP basic entry string.
            EntryString = "LDAP://" & domain
    
    
            'Make the group to check all lowercase (for matching)
            grouptoCheck = grouptoCheck.ToLower()
    
    
            'Use the correct overloaded function of DirectoryEntry
            If (ADlogin <> "" AndAlso ADpassword <> "") Then
                myDE = New DirectoryEntry(EntryString, ADlogin, ADpassword)
            Else
                myDE = New DirectoryEntry(EntryString)
            End If
    
    
            'Filter the directory searcher and get the group names
            Dim myDirectorySearcher As New DirectorySearcher(myDE)
            myDirectorySearcher.Filter = "sAMAccountName=" & username
            myDirectorySearcher.PropertiesToLoad.Add("MemberOf")
            Dim myresult As SearchResult = myDirectorySearcher.FindOne()
    
    
            'Get the number of groups, so they can be itereated
            NumberOfGroups = myresult.Properties("memberOf").Count() - 1
    
    
            While (NumberOfGroups >= 0)
                'Extract the group name from the result set of the index
                tempString = myresult.Properties("MemberOf").Item(NumberOfGroups)
                tempString = tempString.Substring(0, tempString.IndexOf(",", 0))
                tempString = tempString.Replace("CN=", "")
                tempString = tempString.ToLower()
                tempString = tempString.Trim()
    
                If (grouptoCheck = tempString) Then         'We got a winner
                    Return True
                End If
                NumberOfGroups = NumberOfGroups - 1
            End While
    
            Return False                                    'User is not in the specified group
    
    
    
        Catch ex As Exception
    
            Check_If_Member_Of_AD_Group = False             'If all else fails, don't authenticate
    
        End Try
    
    
    End Function
    

    【讨论】:

      【解决方案4】:

      还有另一种获取登录用户名的方法:

      Request.ServerVariables["LOGON_USER"]
      

      【讨论】:

        【解决方案5】:

        之所以能在开发中工作,是因为 VS 的测试网络服务器不是 IIS,而是在您当前的用户帐户下运行。

        如果您希望它在 IIS 中工作,您需要能够正确配置 IIS - 没有其他方法可以做到这一点。

        【讨论】:

          【解决方案6】:

          如果域和用户名在 AD 中指定了类似 "DOMAIN\username" 的内容

          HttpContext.Current.User.Identity.Name.Split('\\')[0] 返回域

          HttpContext.Current.User.Identity.Name.Split('\\')[1] 返回用户名

          【讨论】:

            【解决方案7】:

            这对您想要完成的工作有用吗? Environment.GetEnvironmentVariable("USERNAME").ToString();

            【讨论】:

            • 这不适用于 asp.net 应用程序。
            【解决方案8】:

            我尝试了以上所有方法,但都没有奏效。我也无法进入我的 IIS 来更改设置。我为此挣扎,挣扎,挣扎。我也找了很久没有找到答案。其中一件事是我无法访问已锁定的 IIS,因此我无法更改任何服务器设置。我不得不去做我能够在代码中做的事情。当我研究它时,许多回复说,“这样设置IIS”。 . .嗯,当您可以访问 IIS 时,这很好,但我没有——我必须使用我可以在代码中做的事情。所以,我最终是这样处理的:

            在我的网络配置文件中,我在该部分中添加了以下代码行:

            <system.webServer>
             <security>
              <authentication>
               <anonymousAuthentication enabled="false" />
               <windowsAuthentication enabled="true" />
              </authentication>
            </security>
            </system.webServer>
            

            然后,它在我的本地返回了一个错误,我必须进去修复它。我转到了位于我机器上以下路径中的 applicationhost.config 文件(您的可能不同):

            C:\users\"你的用户名"\My Documents\"yourIISInstallation"\config\applicationhost.config

            我将以下设置更改为“允许”,该设置已设置为“拒绝”:

            <section name="anonymousAuthentication" overrideModeDefault="Deny" />
            

            改为

            <section name="anonymousAuthentication" overrideModeDefault="Allow" />
            

            <section name="windowsAuthentication" overrideModeDefault="Deny" />
            

            改为:

            <section name="windowsAuthentication" overrideModeDefault="Allow" />
            

            <sectionGroup name="authentication">
            

            部分。在我发现这个修复之前,我把头发拉出来了。我希望这可以帮助别人。一旦我将上面的代码放入 webconfig 文件中,它就可以在内网上运行,它只是在我的本地返回错误,但是一旦我将上面的代码添加到我的本地 applicationhost.config 文件中,它就开始在我的本地运行也是。然后,我调用了以下变量来返回 windows 上登录用户的名称:

            HttpContext.Current.User.Identity.Name.ToString().Substring((HttpContext.Current.User.Identity.Name.ToString().IndexOf("\\")) + 1);
            

            干杯!

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-12-09
              • 1970-01-01
              • 2023-03-06
              • 2012-10-20
              • 2018-10-03
              相关资源
              最近更新 更多