Dot-Net

使用 Windows 身份驗證時獲取 Active Directory 資訊?

  • July 11, 2017

我在我的 asp.net MVC 3 應用程序上使用 Windows 身份驗證。有沒有辦法從活動目錄中獲取使用者資訊?

我知道我可以使用 User.Name.Identity 並且適用於登錄名。但是如何從活動目錄中獲取使用者的名字、姓氏,甚至描述或辦公室。這可以通過.net嗎?

**當然!!**如果您使用的是 .NET 3.5 或更高版本,這實際上非常簡單。

基本上,使用 System.DirectoryServices.AccoutManagement 命名空間(在此處閱讀所有相關資訊:在 .NET Framework 3.5 中管理目錄安全主體)。

然後:您需要“找到”使用者並獲取它的屬性 - 使用如下程式碼:

// create domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find the user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "username");

if(user != null)
{
   // access the user's properties in a nice, object-oriented way
}

引用自:https://stackoverflow.com/questions/4961073