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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4961073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:15:00  来源:igfitidea点击:

Getting Active Directory Info when using Windows Authentication?

.netasp.net-mvcactive-directory

提问by twal

I am using Windows authentication on my asp.net MVC 3 app. Is there any way possible to get the users information out of active directory?

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

I know I can user User.Name.Identity and that works for the login name. But what about getting the Users First Name, Last Name and even the Description or Office all from active directory. Is this possible through .net?

我知道我可以使用 User.Name.Identity 并且适用于登录名。但是如何从活动目录中获取用户的名字、姓氏甚至描述或办公室。这可以通过 .net 实现吗?

回答by marc_s

Of course!!If you're using .NET 3.5 or up, it's actually pretty easy.

当然!!如果您使用 .NET 3.5 或更高版本,这实际上非常简单。

Basically, use the System.DirectoryServices.AccoutManagement namespace (read all about it here: Managing Directory Security Principals in the .NET Framework 3.5).

基本上,使用 System.DirectoryServices.AccoutManagement 命名空间(在此处阅读所有相关信息:Managing Directory Security Principals in the .NET Framework 3.5)。

Then: you need to "find" the user and grab it's properties - use code something like this:

然后:您需要“找到”用户并获取其属性 - 使用如下代码:

// 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
}

回答by Kevin Kalitowski

If your code is running under the context of the user that you need information for, it gets even lighter (i.e. Windows Authentication):

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

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

var firstName = user.GivenName;
var lastName = user.Surname;

回答by bhamby

Sounds like you may want to use the System.DirectoryServicesnamespace. Here'sa guide on how you can read properties of a Directory object.

听起来您可能想要使用System.DirectoryServicesnamespace这是有关如何读取 Directory 对象属性的指南。

回答by Pete

In my environment I had to add this to the section in Web.config:

在我的环境中,我必须将其添加到 Web.config 中的部分:

<identity impersonate="true" />