views:

49

answers:

3

I have some code in asp.net ( kindly given by someone else ) to query AD to get user name and email etc.

using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using ActiveDs;

        DirectorySearcher search = new DirectorySearcher(new DirectoryEntry(), string.Format("(samaccountname={0})", id));
        if (search == null)
            return id;
        if (search.FindOne() == null)
            return id;
        DirectoryEntry usr = search.FindOne().GetDirectoryEntry();
        IADsUser oUsr = (IADsUser)usr.NativeObject;
        return string.Format("{0} {1}", usr.Properties["givenname"].Value, usr.Properties["sn"].Value);

However this requires impersonation with an id that's required to be changed every 2 weeks and then updated in the web.config which is often forgotten

Is there any non impersonation code to achieve the same result ?

UPDATE - it's a config tool and it looks up name, email id etc. I like the service a/c idea

Q - How is it possible to run ( impersonate ) just the AD code with a "service" a/c ? any samples/code ?

how do you impersona

A: 

I don't think so, because you need to bind to the domain with valid credentials in order to read from active directory.

Think of the username/password as part of a connection string to a database. I'd request a complex username and password from your domain administrator and request that they give it limited login permissions and set the password to never expire. Then store and use those in your Web.config file.

Nate Bross
A: 

We usually request IT to give us a domain service account. You still need to impersonate, but with a service account, the password will not have to be changed every 2 weeks, and is granted specific rights for the particular function you need it for, so it would mean very low maintenance for you.

code4life
A: 
  1. For your particular purpose, a ServiceAccount shall be added to AD;
  2. If you ASP.NET application is for a LAN in your organization, you could simply forget about providing Username and Password and only provide the root domain. This way, Active directory will search for Windows authenticated user instead of using impersonnation (this assumes that the user accessing your application has the rights to perform the tasks provided by your application).

What exactly does your application need to do?

If your application manages user accounts, groups and OU, then you need to use impersonnation only if the user doing these tasks through the application has no rights of managing the AD with her/his regular user account. This, should not happen. So, event for this, if the user has the proper rights, omitting your credentials will only allow AD to search for the current logged on user.

Will Marcouiller
updated the Ques
Kumar