How to get user details in asp.net Windows Authentication

后端 未结 3 1258
既然无缘
既然无缘 2020-12-28 11:03

I am using windows Authentication and accessing user name as.

IIdentity winId = HttpContext.Current.User.Identity;
string name = winId.Name;
<
相关标签:
3条回答
  • 2020-12-28 11:07

    You can define a MyCustomIdentity by overriding from IIdentity and add your own properties etc.

    0 讨论(0)
  • 2020-12-28 11:19

    Cast it to the specific Identity, for example WindowsIdentity

    0 讨论(0)
  • 2020-12-28 11:20

    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

    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: alt text

    Edit: 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

    0 讨论(0)
提交回复
热议问题