locked
C# ways to access active directory

    Question

  • I have  a C#.net 2008 desktop application that I modified to read the active directory to  obtain what group(s) each user has access to. My company told me the windows and web applications should use  the same logic when accessing the active directory. Since the web application was completed first, I need to find a way  to use the web method of  accessing the active directory.

    Thus I have the following questions about the desktop code listed below versus the web code  listed below also:

    1. Thus can you tell me if there is a way to use the web code in the windows version of accessing the active directory? If so, can you tell me how to modify  the code so it would work in the windows application?
    2. Is there a way to use at least part of the web code. If so, can you show me what code can be used?
    3. If there is no way to use the web code and I should use the windows code that works, can you tell me why the web code would not work?

    --------------
      DESKTOP CODE
    --------------

    The following code is called from various portions of the desktop application. Right after the following class module returns from the application, the following line of code is executed in each section for  the vatious groups that have been setup.

    if ((Thread.CurrentPrincipal.IsInRole("testi1")
    then do  some process.

    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Diagnostics;
    using System.Reflection;
    using System.IO;
    using System.Threading;
    using System.Web;
    using System.Windows.Forms;
    using System.Security.Principal;


    namespace Common.Area
    {
        public class ActiveDirectoryUser
        {
            public ActiveDirectoryUser()
            {
                AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
              
            }

        }
    }
    ----------

      WEB CODE
    ----------
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.DirectoryServices;

    namespace Sup
    {
        public class ActiveDirectoryValidator
        {
            private string _path;
            private string _filterAttribute;

            public ActiveDirectoryValidator(string path)
            {
                _path = path;
            }

            public bool IsAuthenticated(string domainName, string userName, string password)
            {
                string domainAndUsername = domainName + @"\" + userName;
                DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, password);
                try
                {
                    // Bind to the native AdsObject to force authentication.
                    Object obj = entry.NativeObject;
                    DirectorySearcher search = new DirectorySearcher(entry);
                    search.Filter = "(SAMAccountName=" + userName + ")";
                    search.PropertiesToLoad.Add("cn");
                    SearchResult result = search.FindOne();
                    if (null == result)
                    {
                        return false;
                    }
                    // Update the new path to the user in the directory
                    _path = result.Path;
                    _filterAttribute = (String)result.Properties["cn"][0];
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                return true;
            }

        }
    }

    Thursday, September 01, 2011 10:09 PM

Answers

All replies

  • I don't know how you are using your ActiveDirectoryValidator on your web application, but I wouldn't do it that way.

    The "standard" way to validate user identitiy and roles is via an IPrincipal and its associated IIdentity.

    That's why ASP.NET applications (HttpApplication) create the appropriate principal in the authentication fase (AuthenticateRequest).

    ASP.NET even provides out of the box an ActiveDirectoryMembershipProvider.

    So, if you work with a WindowsPrincipal both in the web and windows application, there will be no difference in your code.


    Paulo Morgado
    Friday, September 02, 2011 12:30 AM
  • So you are basically sayinng I can not try to use the web code in the window application? if not can you point me to some code that can be shared by both the web and the windows application?
    Friday, September 02, 2011 2:44 PM
  • I was just pointing that, in my opinion, you overdid it in the web application and did it in the wrong way (again, in my opinion).

    What exactly are the problems you are having using the web code in the windows application?


    Paulo Morgado
    Friday, September 02, 2011 10:25 PM
  • Paul:

    You are correct I am over reacting. I am very sorry about that! My problem is that  I just was moved in my company  from a database position to a programming position. I only  have 2 months of  .net experience. i am the  only  progrmmer at my company.

      programming is no different than being a super experienced data analyst.

      For your information, my next step is make the  IsAuthenticated method work. i am going to try it on Tuesday morning. If you have any  suggestions, just let me know.

    Thanks!

     

     

    Saturday, September 03, 2011 2:03 AM
  • I fell your pain, Wendy. :)

    I'm assuming that your difficulty with the windows application is because you don't have the user's password. That would be reoslved if you always relied on a Principal.

    Take a long look at the IPrincipal and IIdentity interfaces as well as the ActiveDirectoryMembershipProvider.

    You'll probably find out that, using the ActiveDirectoryMembershipProvider, the only changes to the web application are replacing the calls to ActiveDirectoryValidator.IsAuthenticated with calls to HttpContext.Current.User.Identity.IsAuthenticated.


    Paulo Morgado
    Saturday, September 03, 2011 3:24 AM
  • Paulo:

    Thank you for your excellent answer! If you look at my original post for the desktop code, I am using the  IPrincipal and IIdentity interfaces.

    Thus from what you stated in your last reply, if I change the web code to access the HttpContext.Current.User.Identity.IsAuthenticated, I will not need  to pass the password around, correct? if I use the code the way it is, I would be required to  pass  the password around,correct?

    Saturday, September 03, 2011 5:15 AM
  • Thanks Paulo for your help.

    Please refer to the instruction in the similar question of Wendy

    http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/02ec6209-a2d1-479f-9c87-ed5792644c6b


    Martin Xie [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, September 05, 2011 6:00 AM
  • Correct. And since you don't have the password on the windows application, that's what you need.

    Here are some more resources about membership:

    And if you need roles, you can use a role provider:

     


    Paulo Morgado
    Tuesday, September 06, 2011 3:07 AM