簡體   English   中英

檢測使用ASP.NET應用程序登錄計算機的用戶

[英]Detect user logged on a computer using ASP.NET app

我想開發一個可以檢測登錄Window Domain的用戶的ASP.NET應用程序。 這些憑據將用於登錄ASP.NET應用程序。

我怎樣才能做到這一點?

謝謝!

在IIS中,啟用集成Windows身份驗證,並在代碼中,如果您使用:

Request.ServerVariables["LOGON_USER"]

它將返回登錄用戶的Windows用戶名,即MYDOMAIN \\ MYUSERNAME

這是我用來對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;
    }
  }
}

對於ASP.net,您可以使用

HttpContext.Current.User.Identity

如果IIS配置正確(至少沒有匿名登錄)

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

您應該查看活動目錄成員資格提供程序。 它內置於ASP.NET中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM