[英]Getting Active Directory Info when using Windows Authentication?
I am using Windows authentication on my asp.net MVC 3 app. 我在asp.net MVC 3应用程序上使用Windows身份验证。 Is there any way possible to get the users information out of active directory?
有什么办法可以使用户信息脱离活动目录?
I know I can user User.Name.Identity and that works for the login name. 我知道我可以使用User.Name.Identity,它适用于登录名。 But what about getting the Users First Name, Last Name and even the Description or Office all from active directory.
但是如何从活动目录中获取用户的名字,姓氏甚至描述或Office。 Is this possible through .net?
是否可以通过.net?
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命名空间(在此了解所有信息: 在.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
}
If your code is running under the context of the user that you need information for, it gets even lighter (ie Windows Authentication): 如果您的代码是在您需要其信息的用户的上下文中运行的,则代码变得更轻便(例如Windows身份验证):
//Must reference System.DirectoryServices.AccountManagement
var user = UserPrincipal.Current;
var firstName = user.GivenName;
var lastName = user.Surname;
Sounds like you may want to use the System.DirectoryServices
namespace . 听起来您可能想使用
System.DirectoryServices
命名空间 。 Here's a guide on how you can read properties of a Directory object. 这是有关如何读取Directory对象属性的指南。
在我的环境中,我必须将此添加到Web.config的部分中:
<identity impersonate="true" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.