2

I need to use the windows credentials to allow my users to log in an intranet application. I am planning to create a table with usernames and roles and compare the username from Environment.UserName with my table. How safe is to relay on this? Is there a better way to achieve this task?

Thank you in advance.

Peter Bons
  • 26,826
  • 4
  • 50
  • 74

2 Answers2

0

You can do this using active directory authentication:

Bellow is sample code that you can try in your application.

        string domainUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
        string[] paramsLogin = domainUser.Split('\\');

        string domain = paramsLogin[0].ToString();
        string LdapPath = "";
        string strDomainPath = DomainPath();

        LdapPath = string.Format("LDAP://{0}/{1}", DomainName, strDomainPath);

        string username = LoginUser.UserName;
        string password = LoginUser.Password;           


        string domainAndUsername = domain + @"\" + username;
        DirectoryEntry entry = new DirectoryEntry(LdapPath, 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 (result != null)
            {
                IsLoginSucess = true;
                //Do your stuff here
            }

            // Update the new path to the user in the directory
            LdapPath = result.Path;
            string _filterAttribute = (String)result.Properties["cn"][0];
        }
        catch (Exception ex)
        {
            IsLoginSucess = false;                
        }
Bharatsing Parmar
  • 2,435
  • 1
  • 9
  • 18
0

If you are developing in a Windows application, take a look at this:

Authenticate user in WinForms (Nothing to do with ASP.Net) System.Security.Principal.WindowsIdentity.GetCurrent() will give you the current Windows user

If you are developing a Web application, there is built in-support, you would need to have relevant entries in your web.config file

Using windows authentication in asp.net with c#

HttpContext.Current.User.Identity will get you the user identity

Subbu
  • 2,130
  • 1
  • 19
  • 28