Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
using System;
using System.Runtime.InteropServices; //DllImport
namespace GBLogon
{
/// <summary>
/// Summary description for LogonUser.
/// </summary>
public class LogonUserClass
{
//Import LSA functions
[DllImport("advapi32.dll")]
private static extern bool LogonUser(
String lpszUsername,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken
);
private enum LogonTypes
{
LOGON32_PROVIDER_DEFAULT = 0,
LOGON32_LOGON_INTERACTIVE = 2,
LOGON32_LOGON_NETWORK = 3,
LOGON32_LOGON_BATCH = 4,
LOGON32_LOGON_SERVICE = 5,
LOGON32_LOGON_UNLOCK = 7,
LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
LOGON32_LOGON_NEW_CREDENTIALS = 9
}
[DllImport("kernel32.dll")]
private static extern int GetLastError();
// Wrapper for Win32 message formatter.
[DllImport("kernel32.dll",
CharSet=System.Runtime.InteropServices.CharSet.Auto)]
private unsafe static extern
int FormatMessage( int dwFlags,
ref IntPtr pMessageSource,
int dwMessageID,
int dwLanguageID,
ref string lpBuffer,
int nSize,
IntPtr* pArguments);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
public LogonUserClass()
{
//
// TODO: Add constructor logic here
//
}
public static bool AuthenticateUser(String username, String password, ref String errMsg)
{
//define the handles
IntPtr existingTokenHandle = IntPtr.Zero;
String domain;
if(username.IndexOf("\\") > 0)
{
//split domain and name
String[] splitUserName = username.Split('\\');
domain = splitUserName[0];
username = splitUserName[1];
}
else
domain = String.Empty;
try
{
//Get a Security Token
bool isValid = LogonUser(username, domain, password,
(int)LogonTypes.LOGON32_LOGON_INTERACTIVE,
(int)LogonTypes.LOGON32_PROVIDER_DEFAULT,
ref existingTokenHandle);
if (!isValid)
{
int lastWin32Error = Marshal.GetLastWin32Error();
int lastError = GetLastError();
errMsg = GetErrorMessage(lastError);
return false;
//throw new Exception("LogonUser Failed: " + GetErrorMessage(lastError) + " [" + lastWin32Error + " - " + lastError + "]");
}
else
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
//free all handles
if (existingTokenHandle != IntPtr.Zero)
CloseHandle(existingTokenHandle);
}
}
/// <SUMMARY>
/// Formats error message from a Win32 error code.
/// </SUMMARY>
/// <PARAM name="errorCode">
/// Error code.
/// </PARAM>
/// <RETURNS>
/// Formatted error message.
/// </RETURNS>
private unsafe static string GetErrorMessage(int errorCode)
{
// Define flags used to build message.
int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
// Initialize data variables.
int messageSize = 0;
int minBufferSize = 0;
string messageBuffer = String.Empty;
string message = String.Empty;
// We need build a system message as opposed to a message from
// a resource DLL. The operation will require auto memory
// allocation. We will not use formatted arguments.
int dwFlags = FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_IGNORE_INSERTS;
// Set null pointers.
IntPtr pMessageSource = new IntPtr();
IntPtr pArguments = new IntPtr();
// Use default language.
int langID = 0;
// Get message.
messageSize = FormatMessage( dwFlags,
ref pMessageSource,
errorCode,
langID,
ref messageBuffer,
minBufferSize,
&pArguments);
// Include error code in the message.
if (messageSize == 0)
message = String.Format("Error {0} occurred.",
errorCode);
else
message = String.Format("Error {0}: {1}",
errorCode, messageBuffer);
// Return formatted message.
return message;
}
}
}
How to use it in a Logon form for example which contains the btlLogonValidation button, txtUser, txtPassword edit boxes.
User : DOCS\\george.stone
Password: *******
private void btnLogonValidation_Click(object sender, System.EventArgs e)
{
if (!(txtUser.Text.Trim() == "" || txtPassword.Text.Trim() == ""))
{
string s = "";
this.Cursor = Cursors.WaitCursor;
if (LogonUserClass.AuthenticateUser(txtDomain.Text.Trim() + "\\" + txtUser.Text.Trim(),txtPassword.Text.Trim(),ref s))
{
// logon successful
}
else
{
errorProvider1.SetError(btnLogonValidation, s);
}
this.Cursor = Cursors.Default;
}
}