views:

180

answers:

2

Is there a way to use a credential coming from the user's saved password list and use that instead of the local Windows credentials?

I need to look up a user's email address based on their Active Directory username to allow them to register for email updates via an intranet site. This seems easy enough if the user is actually logged into a machine directly that's part of the domain - I can use their identity name to search the AD based on their username:

using( DirectoryEntry root = new DirectoryEntry("LDAP://admachine.domain.local") )
{
  using( DirectorySearcher searcher = new DirectorySearcher(root) )
  {
    // strip the domain from the username and find the user in AD
    var username = Regex.Replace(Page.User.Identity.Name, @".*\\", string.Empty);
    searcher.ReferralChasing = ReferralChasingOption.All;
    searcher.SearchScope = SearchScope.Subtree;
    searcher.Filter = string.Format("(&(objectCategory=user)(objectClass=person)(sAMAccountName={0}))", username);
    var foundUser = searcher.FindOne();

    // error checking occurs here...
    var email = foundUser.Properties["mail"][0].ToString();

    // TODO: stuff with the email address
  }
}

However, if working from a PC at home this doesn't work. Page.Identity.Name resolves to the name I'm logged onto my own PC (MyMachine\Dave), ignoring stored credentials I used to authenticate with my work domain (WorkDomain\dave.downs).

The DirectoryEntry picks up and uses the saved credential just fine, allowing me to actually bind to and search the AD, but I can't find a way of then using it as the var username, which will contain of my local machine username instead.

Is there a way to actually do what I'm trying to do, or am I just going about things the wrong way/hitting my head against a brick wall?

+1  A: 

I assume you are using IIS. Disable Anonymous Access and enable windows authentication. That way anybody who is not in the domain will get a popup that allows them to specify their domain user and password. For users that are coming from a domain enabled server nothing changes. But that way you guarantee that the identity will always resolve to a valide domain user. So this should solve your "I am seeing a non-domain user" problem. Check Windows Authentication Provider for details.

Tobias Hertkorn
But if IIS *was* set to anonymous, how do you explain that his code runs when he's in the company? Should produce the same error, then.
Tomalak
A: 

If they are logged in via Windows Auth, you can use:

System.Security.Principal.WindowsIdentity.GetCurrent().User

which will give you the sid of the logged in user.

Disable anonymous access and integrated security in IIS, force them to log in via basic auth under https. This will give make sure the the current session is running under an authenticated domain user.

Brian Rudolph