locked
C#.net - two active directory group methods RRS feed

  • Question

  • My goal is to try to use the same logic when verifying groups in the active directory for users if they are on the web or in a windows application. However my current problem is the web application is currently using a config file and having users enter their user name and password. The windows application is having the user click on a desktop shortcut and the application obtains the user infromation from windows authenication.

    Is there a way to make code listed in the windows application be more like the web application?
     If not,why not?
     If so, how would you change the code to make to the windows application?

    The windows code is the following:

    AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

    Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

    if ((!Thread.CurrentPrincipal.IsInRole("TEST")))

    {

        MessageBox.Show("Please contact your network administrator if you have any questions",MessageBoxIcon.Error);

        return;

     }

     else

     {

        Application.Run(new newm());

        break;

     }

    The web code is the following:

    using System;

    using System.Collections.Generic;

    using System.Text;

    using System.DirectoryServices;

     

    namespace RtSup

     {

         public class Validator

         {

             private string _path;

             private string _filterAttribute;

     

            public Validator(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

                 {

                     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;

                     }

                     _path = result.Path;

                     _filterAttribute = (String)result.Properties["cn"][0];

                 }

                 catch (Exception ex)

                 {

                     throw new Exception(ex.Message);

                 }

                 return true;

             }

        }

     }

    • Edited by Martin_XieModerator Wednesday, August 31, 2011 8:52 AM Modify the code snippet colorful to make it more readable.
    Tuesday, August 30, 2011 9:55 PM

Answers

All replies

  • Is there a way to make code listed in the windows application be more like the web application?
    If not,why not?
    If so, how would you change the code to make to the windows application?

     

    Hi Wendy,

     

    Yes, you can modify your code to use the same logic of the web application to apply to your Windows Forms Application, as long as you specify Active Directory path and Windows User account information. Please check the following code sample.

     

    We can get domain and username information of current Windows logon user via WindowsIdentity.GetCurrent() method, but cannot get the user Password by design. You’ll need to hard-code it.

    Because: There is no way that you can get the password of an windows(domain) account using WindowsIdentity object. Frankly there is no such method that lets you know the password of an account as that would be a security breach for windows system.

    http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/740f7241-9480-498b-92f9-8a47bb4cb2d2/

     

    using System.DirectoryServices;

    using System.Threading;

    using System.Security.Principal;

     

        public partial class Form1 : Form

        {

            private void Form1_Load(object sender, EventArgs e)

            {

              //WindowsIdentity.GetCurrent().Name; it will get such name as domain\username

              string domainName =  WindowsIdentity.GetCurrent().Name.Split('\\')[0];

              string userName = WindowsIdentity.GetCurrent().Name.Split('\\')[1];

              Validator validator1 = new Validator("LDAP://path");

              if (validator1.IsAuthenticated(domainName, userName, "password") == true)

              {

                  Application.Run(new Form1());

              }

              else

              {

                  MessageBox.Show("Please contact your network administrator if you have any questions");

              }

     

            }

        }

     

        public class Validator

        {

            private string _path;

            private string _filterAttribute;

     

            public Validator(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

                {

                    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;

                    }

                    _path = result.Path;

                    _filterAttribute = (String)result.Properties["cn"][0];

                }

                catch (Exception ex)

                {

                    throw new Exception(ex.Message);

                }

                return true;

            }

        }



    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.

    Wednesday, August 31, 2011 10:02 AM
    Moderator
  • However my current problem is the web application is currently using a config file and having users enter their user name and password. The windows application is having the user click on a desktop shortcut and the application obtains the user.

     

    Hi Wendy, 

    Similarly, as for Windows Forms Application, you can store some settings such as Active Directory path and Windows User account information in app.config file, then read the file.

     

    Tutorials/code samples: How to read/write app.config file at runtime via System.Configuration namespace.
    http://www.codeproject.com/KB/cs/SystemConfiguration.aspx
    http://netindonesia.net/blogs/rahmat.faisal/pages/Read-_2600_-Write-App_2E00_Config.aspx

     

    Additionally, you can Encrypt and Decrypt of your important settings in app.config and/or web.config.

    http://www.codeproject.com/KB/cs/Configuration_File.aspx

     
    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.

    Wednesday, August 31, 2011 10:12 AM
    Moderator
  • 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;
    }

    }
    }

    • Moved by Richard MuellerMVP Friday, September 2, 2011 4:45 PM similar questions asked in csharplanguage forum (From:The Official Scripting Guys Forum!)
    • Merged by Martin_XieModerator Monday, September 5, 2011 3:54 AM Merge it to keep them into the same topic.
    Friday, September 2, 2011 3:50 PM
  • You need to post this in the ASP.NET developer forum for IIS 7.  This is a scripting forum not specific to IIS .  The code you posted is not script.

     


    jv
    Friday, September 2, 2011 3:54 PM