使用Windows身份验证时获取Active Directory信息?

twa*_*wal 13 .net asp.net-mvc active-directory

我在我的asp.net MVC 3应用程序上使用Windows身份验证.有没有办法从用户目录中获取用户信息?

我知道我可以使用User.Name.Identity,这适用于登录名.但是如何从活动目录中获取用户名,姓氏甚至描述或Office.这可以通过.net吗?

mar*_*c_s 23

当然!!如果您使用的是.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
}
Run Code Online (Sandbox Code Playgroud)


Kev*_*ski 5

如果您的代码在您需要信息的用户的上下文中运行,则它会变得更轻(即Windows身份验证):

//Must reference System.DirectoryServices.AccountManagement
var user = UserPrincipal.Current;

var firstName = user.GivenName;
var lastName = user.Surname;
Run Code Online (Sandbox Code Playgroud)