简体   繁体   中英

MVC4: Getting Active Directory User Guid

Once a user is logged into a Windows-Authentication site, how do I get their Active Directoy user guid from the User.

Eg in an Action:

ViewBag.Message = User.Identity.GUID????

You should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find the current user
UserPrincipal user = UserPrincipal.Current;

if(user != null)
{
   // get guid
   var userGuid = user.Guid;
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!

 string userName = user.Identity.Name.Split('\\')[1];

            using (var oRoot = new DirectoryEntry(ConfigurationManager.AppSettings["LDAPDomain"], null, null, AuthenticationTypes.Secure))
            {
                using (var deSearch = new DirectorySearcher(oRoot))
                {
                    deSearch.Filter = string.Format("(&(sAMAccountName={0}))", userName);
                    SearchResult searchResult = deSearch.FindOne();
                    if (searchResult != null)
                    {
                        DirectoryEntry de = searchResult.GetDirectoryEntry();

                    }
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM