How to obtain email address with window authentication

后端 未结 4 1159
礼貌的吻别
礼貌的吻别 2020-12-21 01:28

I am designing a web application using the ASP.net MVC framework. I would like to use Windows Authentication and do Role Checks using the Role Manager SQLRoleProvider.

相关标签:
4条回答
  • 2020-12-21 01:51

    In MVC5 application give the action as given below

      public ActionResult Index()
            {
                string name = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                ViewBag.Name = name;
                ViewBag.Email = uEmail(User.Identity.Name.Replace(@"YOURDOMAIN\", ""));
                return View();
            }
    

    Change the YOURDOMAIN to your domain name. And give the uEmail function as given below. Also add the reference to using System.Security.Principal and using System.DirectoryServices.

    private string uEmail(string uid)
            {
                DirectorySearcher dirSearcher = new DirectorySearcher();
                DirectoryEntry entry = new DirectoryEntry(dirSearcher.SearchRoot.Path);
                dirSearcher.Filter = "(&(objectClass=user)(objectcategory=person)(mail=" + uid + "*))";
    
                SearchResult srEmail = dirSearcher.FindOne();
    
                string propName = "mail";
                ResultPropertyValueCollection valColl = srEmail.Properties[propName];
                try
                {
                    return valColl[0].ToString();
                }
                catch
                {
                    return "";
                }
    
            }
    
    0 讨论(0)
  • 2020-12-21 01:55

    The asp.net membership services database is just a database, which you can execute a query against directly. I dont think the default membership provider has a way to get the email address however.

    0 讨论(0)
  • 2020-12-21 02:01

    You can look up the user's properties in Active Directory. Here is a great article that explains how to do that using System.DirectoryServices and C#:

    http://www.codeproject.com/Articles/6778/How-to-get-User-Data-from-the-Active-Directory

    0 讨论(0)
  • 2020-12-21 02:10

    Here is a sample from some code:

    DirectorySearcher searcher = new DirectorySearcher();    
    searcher.Filter = string.Format("sAMAccountName={0}", _name);    
    SearchResult user = searcher.FindOne();    
    string emailAddr = user.Properties["mail"][0].ToString();
    
    0 讨论(0)
提交回复
热议问题