How to use a logged in person's credentials to search Active Directory? - search

I have a web app (.NET 3.5) which is sending notifications by email to users. In order to do this, I search Active Directory to find each person's email.
At the moment, I am hardcoding my own username and password like so in order to search AD:
Dim entry As New DirectoryEntry("LDAP://companyad", "myUsername", "myPassword", AuthenticationTypes.Secure)
Dim srch As New DirectorySearcher(entry)
srch.Filter = [String].Format("(&(objectClass=person)(sAMAccountName={0}))", "someOtherUsername")
Dim result As SearchResult = srch.FindOne()
Now, obviously, this is not ideal and I don't want those credentials hardcoded. My web app is using Windows Authentication. It also uses impersonation (as the logged in user) to access files and SQL Server. Is there also a way for me to "impersonate" the logged in user in order to search AD?
EDIT 1
I thought I'd better explain why I chose this answer. The problem turned out to not be the multi-hop issue or kerberos as it seems I have set these up correctly.
I had recently changed my app to only allow access to a certain group through the web.config settings. I had previously been only allowing access to myself. I set up the group and added myself to it. I then removed the hardcoded credentials and attempted to run the app WITHOUT RESTARTING my computer.
According to my network admin, I would not be logged on under that new group until I restarted my computer which I think is what was causing my problem. So, Preet's answer is actually the most accurate as I just needed to pass the LDAP path to DirectoryEntry.
EDIT 2
I also needed to register a Service Principal Name.
I ran this:
setspn -A HTTP/[dns name of the site] [machine name]
on my development machine.
Thanks to everyone else for their answers.

Doesn't
Dim entry As New DirectoryEntry("LDAP://companyad")
work?

Why not create a new user for this purpose alone? A user with only searching rights.

I set <identity impersonate="true"/> in my web.config and added the following code to my my page load event handler. It worked fine. Are you sure you are not dealing with a multi hop situation? In that case your app pool account needs to be configured for kerberos authentication to support impersonation in a multihop scenario. More info on this is here: http://support.microsoft.com/kb/329986
Response.Write(User.Identity.Name);
DirectoryEntry entry = new DirectoryEntry("LDAP://[mydomain.net]");
DirectorySearcher srch = new DirectorySearcher(entry);
srch.Filter = string.Format("(&(objectClass=person)(sAMAccountName={0}))", "[user]");
SearchResult result = srch.FindOne();
Response.Write(result.Path);

If you wish to use the Windows logged in user account as the credentials against AD, you have to use the following:
public bool IsExistingUser() {
DirectoryEntry de = new DirectoryEntry(Environment.UserDomainName)
DirectorySearcher ds = new DirectorySearcher(de)
ds.Filter = string.Format("((objectClass=user)(SAMAccountName={0}))", Environment.UserName)
try
SearchResult sr = ds.FindOne();
if (sr != null && sr.DirectoryEntry.Name.Contains(Environment.UserName))
return true;
catch (DirectoryServicesCOMException ex)
catch (COMException ex)
throw new Exception("Can't find logged in user in AD", ex);
return false;
}
Assuming this code would compile and run, it will verify whether the existing logged in user is known by your Domain Controller.
Impersonation is discouraged as it lets litteral password strings travel in your network. So, try to avoid it as much as possible.
EDIT Here's a pretty useful link for AD: Howto: (Almost) Everything In Active Directory via C# I found this post awesome!

Related

C# LDAP Authentication works for one DC, but not another

I have an interesting issue I've been trying to resolve for a few days.
I'm currently working with an Windows Server 2003 machine that is running a standard instance of Active Directory.
The directory contains two domain components (DCs) that both house users that are going to be authorizing against the directory, via my application.
I'm using :
The IP address of the server as the host name
An SSL connection via port 3269
The GSS Negotiate Auth Mechanism
A BaseDN that is a parentDN of both DC's
The sAMAccountName as the login name
The problem is, I cannot successfully authorize any users from DC1, yet all of the ones who belong to DC2 are completely fine and work great. I get this error on DC1 :
8009030C: LdapErr: DSID-0C09043E, comment: AcceptSecurityContext error, data 0, vece
System.DirectoryServices.Protocols.LdapException: The supplied credential is invalid.
However, using Softerra's LDAP Broswer, I can connect in and authorize the same exact user without any issue, so I know the credentials are correct.
From what I can tell, both of these DC's are configured the same... I've browsed both of them for something, anything that is different... but have found nothing that really stands out.
I posted something months ago about this particular setup, and the code I'm using is in that thread as well.
Set callback for System.DirectoryServices.DirectoryEntry to handle self-signed SSL certificate?
Any help here would be much appreciated.
Thanks!
I was able to get this working, but for the life of me I cannot figure out why this was the case. Basically, this error...
8009030C: LdapErr: DSID-0C09043E, comment: AcceptSecurityContext error, data 0, vece System.DirectoryServices.Protocols.LdapException: The supplied credential is invalid.
...was dead on. The issue was that users logging in under what I called DC2 needed to issue the bind with the domain AND sAMAccountName (Ex. LIB\JSmith), as opposed to DC1, which allowed just the sAMAccountName to be entered.
I figured the best way to make this programmatic was to use the principal binding account to query for the DN of the user. From that DN, using some crafty RegEx, I'm able to capture the domain they inherit from, and issue two separate binds.
SearchResultEntry ResultEntry = userResponse.Entries[0];
//Let's get the root domain of the user now using our DN RegEx and that search result
Regex RegexForBaseDN = new Regex(config.LdapAuth.LdapDnRegex);
Match match = RegexForBaseDN.Match(ResultEntry.DistinguishedName);
string domain = match.Groups[1].Value;
//Try binding the user with their domain\username
try
{
var thisUser = new NetworkCredential{
Domain = domain,
UserName = username,
Password = Pin
};
//If this goes well, we'll continue forward
ldapconn.Bind(thisUser);
}
//If that doesn't work, try biding them with the highest level domain
catch (LdapException ex)
{
if (ex.ErrorCode.Equals(LdapErrorCodes.LDAP_INVALID_CREDENTIALS))
{
var thisUserOnce = new NetworkCredential{
Domain = config.LdapAuth.LdapDomain,
UserName = username,
Password = Pin
};
//If this goes well, we'll continue forward
ldapconn.Bind(thisUserOnce);
}
}
It's not nearly as elegant as I would have wanted, but it does work for this particular scenario.
However, I'm still really interested in why the naming conventions are different depending on which DC the user inherit's from.

Grails - Spring Security Account Creation

I am using the Spring Security Core plugin and can successfully log users in and out of my application. However, when the user successfully signs up, I don't understand how to set that user's security context on the signup postback so that they can be redirected to a secure page without having to log in again. Any help is welcome. Thanks.
The other link you reference is 2 years old. Since then I've added a reauthenticate method to SpringSecurityService. See section "6.2 SpringSecurityService" in the docs:
http://grails-plugins.github.com/grails-spring-security-core/docs/
I eventually came upon this link, which does the trick: https://stackoverflow.com/a/7112838/469106
Here are the contents of that link:
If you don't have the password, you can load the user via
def user = User.findByUsername(username)
and setting the authority array in the 3-parameter constructor. Create the auths via
GrantedAuthority[] auths = user.authorities.collect { new GrantedAuthorityImpl(it.authority) }
Then you can omit the call to authenticate() and use:
SecurityContextHolder.context.authentication = new UsernamePasswordAuthenticationToken(username, 'unknown', auths)

Why does CredentialCache.DefaultCredential contain empty strings for domain, username, and password

Does anyone have any ideas as to why CredentialCache.DefaultCredential would return an ICredential instance with empty strings for domain, username, and password? I'm running a WCF service on IIS 7.5. It works fine on one server but never works on another. I have verified that the IIS application has Windows Authentication enabled....
Here is how it's being used:
string url = string.Format("{0}/departments/finance/_vti_bin/listdata.svc", _IntranetAddress);
var financeDataContext = new FinanceDataContext(new Uri(url))
{
Credentials = CredentialCache.DefaultCredentials
};
I am not sure how it is working in one of your servers? I hope you already read this
http://msdn.microsoft.com/en-us/library/system.net.credentialcache.defaultcredentials.aspx
but it clearly says "The ICredentials instance returned by DefaultCredentials cannot be used to view the user name, password, or domain of the current security context."
The NetworkCredential returned from CredentialCache.DefaultCredential is just a placeholder. If you look at it using the Debugger, you'll see that it's of type SystemNetworkCredential. Internal API check for this type to see if integrated authentication should be used or not. There are other ways to get the current username (like WindowsIdentity.GetCurrent()).
EDIT:
To specify impersonation for a WCF operation, add this attribute to the method implementing a contract:
[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public void SomeMethod()
{
// do something here
}

SharePoint session persist across several users?

I have a custom web part that starts by getting a current user login name like this:
protected static string iAm = System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].Split("\\".ToCharArray())[1].ToLower().
Then it passes this string to a bbl class and fetches a user id:
`IDataReader _drInfo = cisf_BLL.bll_MyInfo.drGetMyInfo(iAm);
while (_drInfo.Read())
{
iUser_Ident = _drInfo.GetInt32(30);
}
`After that it passes the user id integer to another method that fetches user's training record:
_drUserTraining = bll_Training.drGet_required_training_records(iUser_Ident);
_drUserTrainingCompleted = bll_Training.drGet_completed_training_records(iUser_Ident);
This information is then displayed in a tab container with three tab such as "Overdue", "Required", and "Completed".
The problem I'm having is this: I'm logged into SharePoint collaboration site with my domain user name and all my training is displayed just fine. If my someone else then logs in to the SP Portal that user sees my training and not his, even though this user has logged in with his unique credential using a common access card, just as I.
Somehow some strange session seems to persist and I was hoping someone out here has encountered this anomaly.
Thanks in advance!
Risho
You are misusing static - a static property is stored once per web server process, not once per user.
Not an answer, but code improvement: there is much simplyer way to get current user name/id
SPUser user = Microsoft.SharePoint.[SPContext][1].Current.Web.CurrentUser;
user.ID;
user.Email;
user.Name
user.LoginName;
user.Grups;
....
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spuser_members.aspx

Strange behavoir of RunWithElevatedPrivileges in Console Aplication with FBA

I have a named site collection where FBA is on und i use ActiveDirectoryMembershipProvider.
We have a farm administrator domain\administrator. He is not explicitly sitecollection administrator.
I created a sample console application that I run under the domain\administrator account.
In the code is something like that:
using (SPSite site = new SPSite(serverUrl))
{
using (SPWeb web = site.OpenWeb())
{
Console.WriteLine(web.CurrentUser.LoginName);
Console.WriteLine(WindowsIdentity.GetCurrent().Name);
string userName = "domain\\testuser";
SPUser spUser = web.EnsureUser(userName);
SPGroup group = web.SiteGroups["GroupName"];
group.AddUser(spUser);
group.Update();
}
}
The console output is domain\administrator however I become an AccessDenied exception when I try to add user to the group.
However when I run this with RunWithElevetadPrivileges (which according to all posts I read should have no influence in console app) and set AllowUnsafeUpdates = true (the same story) the code goes smoothly through, no exception thrown and the user is added to the group. The interesting thing is that the user that is written to the console output is still domain\administrator.
So my question is: WTF? Is there a better way? Why is this happenning? Has anyone already had this problem? Should I use another membershipprovider?
Small hint: When the FBA is off I become no exceptions.
RunWithElevatedPrivileges runs code with permissions of user that the application pool runs. It can be other than Administrator. Are you sure you get the same result with RunWithElevatedPrivileges?
Anyway, a better, more reliable way of elevating privileges is to pass system users User token in SPSite constructor. Try it.

Resources