使用ASP.NET应用程序检测用户是否已登录计算机

3

我想开发一个ASP.NET应用程序,可以检测到Windows域上的用户登录。这些凭据将用于登录ASP.NET应用程序。

我该如何做呢?

谢谢!

5个回答

8
在IIS中,打开集成Windows身份验证功能,在代码中,如果您使用以下内容:
Request.ServerVariables["LOGON_USER"]

它将返回已登录用户的Windows用户名,即MYDOMAIN\MYUSERNAME。


如果用户在IIS上进行匿名登录,我将无法看到他的数据。这仅适用于运行IIS的计算机。 - VansFannel

1
这是我用来对接Active Directory进行身份验证的C#代码。
using System;
using System.DirectoryServices;

namespace XYZcompany.Enterprise
{
  public class AuthenicationMgr
  {
    private static readonly int AD_ERR_LOGON_FAIL = -2147023570;
    private static readonly string _path = "LDAP://xxx.yyy.ggg";
    private static readonly string _domain = "xxx.yyy.ggg";

    public static bool IsAuthenticated(string username, string pwd)
    {
      bool authenticatedFlag = true;
      string domainAndUsername = _domain + "\\" + username;
      DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
      try
      {
        // Bind to the native AdsObject to force authentication.
        Object obj = entry.NativeObject;
        DirectorySearcher search = new DirectorySearcher(entry);

        search.Filter = "(SAMAccountName=" + username + ")";
        search.PropertiesToLoad.Add("cn");
        SearchResult result = search.FindOne();

        if (result == null)
        {
          authenticatedFlag = false;
        }
        else
        {
          authenticatedFlag = true;
        }
      }
      catch (System.Runtime.InteropServices.COMException ex)
      {
        if (ex.ErrorCode == AD_ERR_LOGON_FAIL)
        {
          authenticatedFlag = false;
        }
        else
        {
          throw new ApplicationException("Unable to authenticate user due to system error.", ex);
        }
      }
      return authenticatedFlag;
    }
  }
}

我不是现在需要它,但以后可能会需要。谢谢! - VansFannel

1

对于ASP.net,您可能可以使用

HttpContext.Current.User.Identity

如果IIS配置正确(没有匿名登录,至少如此)

0

你应该研究一下活动目录成员提供程序。它是内置在ASP.NET中的。


-1
System.Security.Principal.WindowsIdentity.GetCurrent().User.ToString

1
这在ASP.NET应用程序中不起作用,因为它会返回IIS的凭据,而不是已登录的用户。 - Lennaert
我每天都使用它,对我和所有使用该网站的用户来说都很好用。 - Kieran Senior
2
那么你可能正在使用身份模拟,这是可怕的且不建议使用。 - Scott Arrington

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接