ASP.NET获取当前用户名

问题描述 投票:6回答:8

我正在尝试使用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
8个回答
4
投票

在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 Impersionation。如果您不需要ASP.NET Impersonation并处理线程标识,则可以忽略Environment.UserName if if and just use 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身份验证”。如果还检查了“启用匿名访问”,它将只使用匿名,所以你应该关掉那个...


2
投票

这是我发现的(某处),最终使用。希望它可以帮助其他人!

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

2
投票

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

Request.ServerVariables["LOGON_USER"]

1
投票

它在开发中工作的原因是因为VS的测试Web服务器不是IIS,而是在您当前的用户帐户下运行。

如果您希望在IIS中使用它,则需要能够正确配置IIS - 没有其他方法可以执行此操作。


1
投票

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

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

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


0
投票

这会对你想要完成的事情有用吗? Environment.GetEnvironmentVariable("USERNAME").ToString();


0
投票

我尝试了上述所有内容,但没有一个有效。我也无法进入我的IIS来更改设置。我努力奋斗,奋力拼搏。我也搜索了很长时间没有找到答案。其中一件事是我无法访问被锁定的IIS,因此我无法更改任何服务器设置。我不得不在代码中使用我能做的事情。当我研究它时,许多回复说,“设置这样的IIS”。 。 .well,当你有权访问IIS时,这很棒,但我没有 - 我必须使用我在代码中可以做的事情。所以,我最终像这样处理它:

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

<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文件中,它就在Intranet上工作,它只是在我的本地返回错误,但是一旦我将上面的内容添加到我的本地applicationhost.config文件中,它就开始在我的本地工作了同样。然后,我调用以下变量来返回Windows上登录用户的名称:

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

干杯!

© www.soinside.com 2019 - 2024. All rights reserved.