Query user data logged in Windows Authentication

7

In my application I use authentication mode="Windows" as a form of authentication.

In this way, I can know the user name, referring to the field in the AD and the domain of the user using HttpContext.Current.User.Identity.Name , ex: DOMAIN\username . I would like to know if I can retrieve other user information, such as email, description, etc.

Using ActiveDirectoryMembershipProvider I have access to the other fields, such as userprincipalname, samaccountname, mail, etc . I would like to know if using authentication mode="Windows" I can return this data. If not, can I return some other data besides authentication mode="Windows" ?

    
asked by anonymous 27.05.2015 / 15:47

1 answer

4

I wrote a Helper (a static class with static methods) with a method that finds the users of a domain with the respective information and another that details a specific user:

using MeuProjeto.ViewModels;
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Web;

namespace MeuProjeto.Helpers
{
    public static class ActiveDirectoryHelper
    {
        public static ActiveDirectoryUserViewModel GetADUser(String search)
        {
            using (var context = new PrincipalContext(ContextType.Domain, "meudominiodoad"))
            {
                var result = UserPrincipal.FindByIdentity(context, search);

                var groups = result.GetGroups().ToList();

                return new ActiveDirectoryUserViewModel
                {
                    DisplayName = result.DisplayName,
                    Email = result.EmailAddress,
                    Mapped = true,
                    UserName = result.UserPrincipalName,
                    Groups = result.GetGroups()
                };
            }
        }

        public static IEnumerable<ActiveDirectoryUserViewModel> GetADUsers()
        {
            using (var context = new PrincipalContext(ContextType.Domain, "meudominiodoad"))
            {
                using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                {
                    foreach (var result in searcher.FindAll())
                    {
                        DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                        yield return new ActiveDirectoryUserViewModel
                        {
                            DisplayName = (de.Properties["displayName"].Value ?? de.Properties["name"].Value).ToString(),
                            UserName = de.Properties["sAMAccountName"].Value.ToString()
                        };
                    }
                }
            }
        }
    }
}

Here are the Properties of DirectoryEntry that you can use .

    
29.05.2015 / 22:35