Microsoft KB Archive/841699

= How to validate Windows user rights in a Visual Basic .NET or Visual Basic 2005 application =

Article ID: 841699

Article Last Modified on 5/18/2007

-

APPLIES TO


 * Microsoft Visual Basic 2005
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-





SUMMARY
''This article discusses how to validate a user's Microsoft Windows user name and password in a Microsoft Visual Basic .NET or Microsoft Visual Basic 2005 application. This article includes a code sample that validates a user in a Visual Basic .NET or Visual Basic 2005 application.

After the Visual Basic .NET or Visual Basic 2005 application validates the user's Windows user name and password, the application also verifies that the Windows user has administrative credentials. The application performs the validation by doing the following:''


 * The application passes the user name and password to the LogonUser function.
 * The LogonUser function validates the user name and password and returns True if the user name and the password are valid.
 * If the user name and password are valid, the LogonUser function receives a handle to the token that represents the Windows user.
 * The WindowsIdentity object uses this token to represent the Windows user in the application.
 * The WindowsPrincipal object uses the WindowsIdentity object to verify that the Windows user has administrative credentials.
 * If the Windows user has administrative credentials, the application permits the Windows user to continue. If the Windows user does not have administrative credentials, the Windows user cannot continue and must quit the Visual Basic .NET application.



IN THIS TASK

 * INTRODUCTION
 * Requirements
 * Create a Visual Basic .NET application
 * Design the Windows Form to implement validation
 * Write code to validate the Windows user in your Visual Basic .NET application
 * Verify that your Visual Basic .NET application works
 * REFERENCES



INTRODUCTION
This step-by-step article describes how to verify a user's Windows user name and password in an application that you create by using Visual Basic .NET. This article also describes how to provide functionality to a Windows user based on the user rights that have been granted to the Windows user account.

back to the top

Requirements
This article assumes that you are familiar with the following topics:
 * Windows applications
 * Visual Basic .NET or Visual Basic 2005 programming

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Microsoft Visual Studio .NET or Microsoft Visual Studio 2005
 * Microsoft .NET Framework
 * Microsoft Windows Platform Software Development Kit (SDK)

back to the top

Create a Visual Basic .NET or Visual Basic 2005 application
To create an application that verifies the user name and password, follow these steps:
 * 1) Start Visual Studio .NET or Visual Studio 2005.
 * 2) On the File menu, point to New, and then click Project. The New Project dialog box appears.
 * 3) Under Project Types, click Visual Basic Projects.

Note In Visual Studio 2005, click Visual Basic under Project Types.
 * 1) Under Templates, click Windows Application.
 * 2) In the Name box, type MyApp, and then click OK. By default, a Windows Form that is named Form1 is created.

back to the top

Design the Windows Form to implement validation
You can design the Windows Form to accept the user name and password at runtime by using TextBox controls. Then, you can make the application verify the Windows user's user rights when the Windows user clicks a Button control. To do this, follow these steps:  On the View menu, click Toolbox. In the Toolbox, double-click the TextBox control two times to add two TextBox controls to the Form1 form. By default, the TextBox1 TextBox control and the TextBox2 TextBox control are added to the Form1 form. Position the TextBox controls so that the TextBox2 TextBox control is below the TextBox1 TextBox control and is vertically aligned to the TextBox1 TextBox control. Right-click the TextBox2 TextBox control, and then click Properties. In the Properties window, set the PasswordChar property to * . In the Toolbox, double-click the Button control to add a Button control to the Form1 form. By default, the Button1 Button control is added to the Form1 form.</li> Right-click the Button1 Button control, and then click Properties.</li> In the Properties window, set the Text property to Validate User .</li> In Solution Explorer, right-click MyApp, point to Add, and then click Add New Item. The Add New Item - MyApp dialog box appears.</li> Under Templates, click Windows Form, and then click Open. By default, a Windows Form that is named Form2 is created.</li> Add a Button control to the Form2 form. By default, the Button1 Button control is added to the Form2 form.</li> Right-click the Button1 Button control, and then click Properties.</li> In the Properties window, set the Text property to Add Numbers .</li> In the Toolbox, double-click the Label control to add a Label control to the Form2 form. By default, the Label1 Label control is added to the Form2 form.</li> Right-click the Label1 Label control, and then click Properties.</li> In the Properties window, set the Size property to 200, 56 .</li>  Double-click the Button1 Button control, and then add the following code to the Button1_Click event handler: Dim firstnum, secondnum, result As Integer firstnum = InputBox(&quot;Enter the first number&quot;) secondnum = InputBox(&quot;Enter the second number&quot;) result = firstnum + secondnum MessageBox.Show(&quot;The sum of the two numbers is:&quot; & result) </li></ol>

back to the top

Write code to validate the Windows user in your Visual Basic .NET application
You can use the LogonUser Win32 API to verify the user name and password. The LogonUser function is declared in the Advapi32.dll library. You can call the LogonUser function from your Visual Basic .NET application by using the Declare statement.

You must pass the domain name, the user name, and the password to the LogonUser function. The LogonUser function validates the user by using these parameters and then returns a Boolean value. If the function succeeds, you receive a handle to a token that represents the Windows user. The WindowsIdentity object uses this token to represent the Windows user in your Visual Basic .NET or Visual Basic 2005 application. The WindowsPrincipal object uses this WindowsIdentity object to verify the Windows user's user rights.

To write code that implements validation in your Visual Basic .NET or Visual Basic 2005 application, follow these steps: <ol> In Solution Explorer, right-click Form1.vb, and then click View Code.</li>  Add the following code at the top of the Form1 form: Imports System.Security.Principal Imports System.Security.Permissions Imports System.Runtime.InteropServices Imports System.Environment </li>  Locate the following code: End Class </li>  Add the following code before the code that you located in step 3: 'The LogonUser function tries to log on to the local computer 'by using the specified user name. The function authenticates 'the Windows user with the password provided. Private Declare Auto Function LogonUser Lib &quot;advapi32.dll&quot; (ByVal lpszUsername As [String], _  ByVal lpszDomain As [String], ByVal lpszPassword As [String], _   ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _   ByRef phToken As IntPtr) As Boolean

'The FormatMessage function formats a message string that is passed as input. <DllImport(&quot;kernel32.dll&quot;)> _ Public Shared Function FormatMessage(ByVal dwFlags As Integer, ByRef lpSource As IntPtr, _  ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByRef lpBuffer As [String], _   ByVal nSize As Integer, ByRef Arguments As IntPtr) As Integer End Function

'The CloseHandle function closes the handle to an open object such as an Access token. Public Declare Auto Function CloseHandle Lib &quot;kernel32.dll&quot; (ByVal handle As IntPtr) As Boolean </li>  Locate the following code: End Class </li> <li> Add the following code before the code that you located in step 5: 'The GetErrorMessage function formats and then returns an error message 'that corresponds to the input error code. Public Shared Function GetErrorMessage(ByVal errorCode As Integer) As String Dim FORMAT_MESSAGE_ALLOCATE_BUFFER As Integer = &H100 Dim FORMAT_MESSAGE_IGNORE_INSERTS As Integer = &H200 Dim FORMAT_MESSAGE_FROM_SYSTEM As Integer = &H1000

Dim msgSize As Integer = 255 Dim lpMsgBuf As String Dim dwFlags As Integer = FORMAT_MESSAGE_ALLOCATE_BUFFER Or FORMAT_MESSAGE_FROM_SYSTEM Or FORMAT_MESSAGE_IGNORE_INSERTS

Dim lpSource As IntPtr = IntPtr.Zero Dim lpArguments As IntPtr = IntPtr.Zero 'Call the FormatMessage function to format the message. Dim returnVal As Integer = FormatMessage(dwFlags, lpSource, errorCode, 0, lpMsgBuf, _           msgSize, lpArguments) If returnVal = 0 Then Throw New Exception(&quot;Failed to format message for error code &quot; + errorCode.ToString + &quot;. &quot;) End If   Return lpMsgBuf End Function </li> <li>In Solution Explorer, right-click Form1.vb, and then click View Designer.</li> <li> Double-click the Button1 Button control, and then add the following code to the Button1_Click event handler: Dim tokenHandle As New IntPtr(0) Try

Dim UserName, MachineName, Pwd As String 'The MachineName property gets the name of your computer. MachineName = System.Environment.MachineName UserName = TextBox1.Text Pwd = TextBox2.Text Dim frm2 As New Form2 Const LOGON32_PROVIDER_DEFAULT As Integer = 0 Const LOGON32_LOGON_INTERACTIVE As Integer = 2 tokenHandle = IntPtr.Zero 'Call the LogonUser function to obtain a handle to an access token. Dim returnValue As Boolean = LogonUser(UserName, MachineName, Pwd, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, tokenHandle)

If returnValue = False Then 'This function returns the error code that the last unmanaged function returned. Dim ret As Integer = Marshal.GetLastWin32Error Dim errmsg As String = GetErrorMessage(ret) frm2.Show frm2.Label1.Text = errmsg frm2.Button1.Visible = False Else 'Create the WindowsIdentity object for the Windows user account that is     'represented by the tokenHandle token. Dim newId As New WindowsIdentity(tokenHandle) Dim userperm As New WindowsPrincipal(newId) 'Verify whether the Windows user has administrative credentials. If userperm.IsInRole(WindowsBuiltInRole.Administrator) Then frm2.Button1.Text = &quot;Add Numbers&quot; frm2.Label1.Text = &quot;Click this button to add two numbers&quot; frm2.Show Else frm2.Label1.Text = &quot; You do not have administrative credentials.&quot; frm2.Button1.Visible = False frm2.Show End If  End If

'Free the access token. If Not System.IntPtr.op_Equality(tokenHandle, IntPtr.Zero) Then CloseHandle(tokenHandle) End If Catch ex As Exception MessageBox.Show(&quot;Exception occurred. &quot; + ex.Message) End Try </li></ol>

back to the top

Verify that your Visual Basic .NET application works
To verify that the validation has completed correctly, follow these steps:
 * 1) On the Build menu, click Build Solution.
 * 2) On the Debug menu, click Start.
 * 3) In the TextBox1 box, type a user name.
 * 4) In the TextBox2 box, type a password.
 * 5) Click Validate User.

back to the top

<div class="references_section">