Sometimes it’s handy to grab either a username or email address (why not both?) from active directory. Below are the steps I believe you’ll need to get going quickly. In my example, I’m using VS2012 and .net 4.5.
1. Set your app to use windows authentication, you’ll need to set these to debug in VS:
Your web.config:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Windows" />
<identity impersonate="true" />
<authorization>
<allow users="*" />
</authorization>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
</configuration>
Your project settings:
2. Now in your application, add a reference to System.DirectoryServices:
3. And in your code file:
using System.DirectoryServices;
4. A little function to search through active directory:
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 "";
}
}
5. And finally, how you can use:
string uName = "";
uName = uEmail(HttpContext.Current.User.Identity.Name.Replace(@"yourdomain\", ""));
Hope you enjoy! You can also use this method to retrieve other AD details (groups, full name, etc.).
沒有留言:
張貼留言