-1

I'm trying to add windows authentication to my login form. I've research on authentication but all i see is authentication for asp.net. can someone please help me, i'm kinda stuck here.

I found some help online but its half baked... need help to add connection string and query to database in code below.

    public partial class Form1 : Form
{
    [System.Runtime.InteropServices.DllImport("advapi32.dll")]
    public static extern bool LogonUser(string userName, string domainName, string password);
    public Form1()
    {
        InitializeComponent();
    }

    private void btnLogin_Click(object sender, EventArgs e)
    {
        bool issuccess = false;
        string username = GetloggedinUserName();

        if (username.ToLowerInvariant().Contains(txtUserName.Text.Trim().ToLowerInvariant()))
        {
            issuccess = IsValidateCredentials(txtUserName.Text.Trim(), txtPwd.Text.Trim(), txtDomain.Text.Trim());
        }

        if (issuccess)
            MessageBox.Show("Successfully Login !!!");
        else
            MessageBox.Show("User Name / Password is invalid !!!");
    }

    private string GetloggedinUserName()
    {
        System.Security.Principal.WindowsIdentity currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
        return currentUser.Name;
    }

    private bool IsValidateCredentials(string userName, string password)
    {
        IntPtr tokenHandler = IntPtr.Zero;
        bool isValid = LogonUser(userName, domain, password, 2, 0, ref tokenHandler);
        return isValid;
    }

}

Kith Black
  • 1
  • 1
  • 3
  • Did this not help you if you are saying that you researched it [https://code.msdn.microsoft.com/windowsdesktop/Add-Window-Authentication-833ba913] ? – ArtleMaks Feb 24 '16 at 14:05
  • Can you explain the scenario, where you need this in service for client, or standalone. Also provide the snippet of code which you have tried already. – MKMohanty Feb 24 '16 at 14:08
  • The link you've posted doesn't exist. – Kith Black Feb 25 '16 at 09:48

1 Answers1

1

Considering you need a standalone application for windows authentication.

Step 1: GetUserName : from

System.Security.Principal.WindowsIdentity.GetCurrent().Name;
or
Environment.UserName

difference between them you can get from here

Step 2: Now use

 [System.Runtime.InteropServices.DllImport("advapi32.dll")] 
 public static extern bool LogonUser(string userName, string domainName,string password, int LogonType, int LogonProvider, ref IntPtr phToken); 

it will give the result if you use the correct username and password, hope this helps.

Community
  • 1
  • 1
MKMohanty
  • 926
  • 6
  • 22