Authenticating Windows NT Credentials via Form Input

-------------------------------------------------------
Goto blog home
Visit my new blog dedicated to Internet of Things, Embedded Programming & Automation
-------------------------------------------------------
This week has been a busy one with little time for research. But then this topic turned out to be an exciting one. There will be a standard windows form (the web/asp version might need adjustments) with three textboxes: (1) txtUserName, (2) txtPassword and (3) txtDomain. The end user will enter any windows credentials into this form; and the code logic will validate the entered information is true or false - and you shall have an enterprise class login interface that you will often find in off the shelf enterprise products.

The C#.NET code lising is provided below (it can be done in other languages and platforms also):
------------------------------
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsAuthenticationDialog
{
public partial class Login : Form
{
[DllImport("ADVAPI32.dll", EntryPoint = "LogonUserW", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

public Login()
{
InitializeComponent();
}

private void btnLogin_Click(object sender, EventArgs e)
{
IntPtr _ptr = IntPtr.Zero;
bool _result = LogonUser(txtUserName.Text, txtDomain.Text, txtPassword.Text, 2, 0, ref _ptr);

if (_result)
{
MessageBox.Show("Access granted!");
}
else
{
MessageBox.Show("Incorrect credentials!");
}
}
}
}


The above code is actually calling a windows API (which is unmanaged) by importing the API DLL and declaring the LogonUser() function and passing appropriate arguments.

For detailed literature on using windows APIs or interoperability with unmanaged libraries you might want to consider the following references:

(1) http://msdn.microsoft.com/en-us/library/aa984739(VS.71).aspx
(2) http://www.pinvoke.net