如何让asp.net Windows身份验证的用户详细信息 [英] How to get user details in asp.net Windows Authentication

查看:95
本文介绍了如何让asp.net Windows身份验证的用户详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Windows身份验证和访问用户名。

I am using windows Authentication and accessing user name as.

IIdentity winId = HttpContext.Current.User.Identity;
string name = winId.Name;

但我想获得其他细节,如用户的全名和EMAILID。

but i want to get other details like User full name and EmailID.

推荐答案

既然你是Windows网络上,那么你需要查询Active Directory来搜索用户,然后得到它的属性,如电子邮件

Since you're on a windows network, then you need to query the Active directory to search for user and then get it's properties such as the email

下面是一个例子功能 DisplayUser 给定的的IIdentity 在Windows身份验证的网络上,找到用户的电子邮件

Here is an example function DisplayUser that given an IIdentity on a windows authenticated network, finds the user's email:

public static void Main() {
    DisplayUser(WindowsIdentity.GetCurrent());
    Console.ReadKey();    
}

public static void DisplayUser(IIdentity id) {    
    WindowsIdentity winId = id as WindowsIdentity;
    if (id == null) {
        Console.WriteLine("Identity is not a windows identity");
        return;
    }

    string userInQuestion = winId.Name.Split('\\')[1];
    string myDomain = winId.Name.Split('\\')[0]; // this is the domain that the user is in
     // the account that this program runs in should be authenticated in there                    
    DirectoryEntry entry = new DirectoryEntry("LDAP://" + myDomain);
    DirectorySearcher adSearcher = new DirectorySearcher(entry);

    adSearcher.SearchScope = SearchScope.Subtree;
    adSearcher.Filter = "(&(objectClass=user)(samaccountname=" + userInQuestion + "))";
    SearchResult userObject = adSearcher.FindOne();
    if (userObject != null) {
        string[] props = new string[] { "title", "mail" };
        foreach (string prop in props) {
            Console.WriteLine("{0} : {1}", prop, userObject.Properties[prop][0]);
        }
    }
}

给出了这样的:

gives this:

编辑:如果你得到错误的用户/密码错误
的code下运行,必须有访问权的用户域的帐户。如果你在asp.net中运行code,则该Web应用程序必须在与域访问凭据的应用程序池运行。请参见这里更多信息

If you get 'bad user/password errors' The account that the code runs under must have access the users domain. If you run code in asp.net then the web application must be run under an application pool with credentials with domain access. See here for more information

这篇关于如何让asp.net Windows身份验证的用户详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆