Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Obtaining UserID and Password 1

Status
Not open for further replies.

hjmc

Technical User
Nov 20, 2002
38
GB
Can somebody kindly tell me how I can use a standard "Enter Username and Password" screen and have the system verify the info.

I am using C# and the app will run on either win NT or 2000

Thanks for any help
 
Do you mean you want to verify the username / pw in accordance with the active directory?

Or do you just want to "*" over a textbox?

Tom
 
Tom thanks for the reply.

First of all Tom I would like to know if I can use the standard login window (if such a one exists) and then
I would like to verify the obtained ID/PW in the active directory.
 
I do not 'think' there is a standard p/w control, just make youe own by added two textboxes to a new usercontrol.

There is a fair bit of infomation on active dir on Csharp corner

Hope this helps

Tom
 
I put here a class that I am using to do this job. You have to implement a simple dialog Logon form with : user , password edit boxex and logon button. When click on the logon button call the AuthenticateUser() method of this class.

Code:
using System;
using System.Runtime.InteropServices;	//DllImport


namespace GBLogon
{
	/// <summary>
	/// Summary description for LogonUser.
	/// </summary>
	public class LogonUserClass
	{
		//Import LSA functions
		[DllImport(&quot;advapi32.dll&quot;)]
		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(&quot;kernel32.dll&quot;)]
		private static extern int GetLastError();

		// Wrapper for Win32 message formatter.
		[DllImport(&quot;kernel32.dll&quot;,
			 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(&quot;kernel32.dll&quot;)]
		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(&quot;\\&quot;) > 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(&quot;LogonUser Failed: &quot; + GetErrorMessage(lastError) + &quot; [&quot; + lastWin32Error + &quot; - &quot; + lastError + &quot;]&quot;);
				}
				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=&quot;errorCode&quot;>
		/// 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(&quot;Error {0} occurred.&quot;,
					errorCode);
			else
				message = String.Format(&quot;Error {0}: {1}&quot;,
					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() == &quot;&quot; || txtPassword.Text.Trim() == &quot;&quot;))
{
	string s = &quot;&quot;;
	this.Cursor = Cursors.WaitCursor;
	if (LogonUserClass.AuthenticateUser(txtDomain.Text.Trim() + &quot;\\&quot; + txtUser.Text.Trim(),txtPassword.Text.Trim(),ref s))
	{
		// logon successful
	}
	else
	{						
		errorProvider1.SetError(btnLogonValidation, s);

	}
	this.Cursor = Cursors.Default;				
}
}

-obislavu-


 
Obislavu,

Many many thanks for the time and effort you have made in replying. Greatly appreciate it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top