How to validate Windows user rights in a Visual Basic .NET or Visual Basic 2005 application (841699)
The information in this article applies to:
- Microsoft Visual Basic 2005
- Microsoft Visual Basic .NET (2003)
- Microsoft Visual Basic .NET (2002)
SUMMARYThis 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.
INTRODUCTIONThis 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 topRequirementsThis 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 topCreate a Visual Basic .NET or Visual Basic 2005 applicationTo create an application that verifies the user name and password, follow these steps: - Start Visual Studio .NET or Visual Studio 2005.
- On the File menu, point to New, and then click Project. The New Project dialog box appears.
- Under Project Types, click Visual Basic Projects.
Note In Visual Studio 2005, click Visual Basic under Project Types. - Under Templates, click Windows Application.
- 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 validationYou 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.
- Right-click the Button1 Button control, and then click Properties.
- In the Properties window, set the Text property to Validate User.
- In Solution Explorer, right-click MyApp, point to Add, and then click Add New Item. The Add New Item - MyApp dialog box appears.
- Under Templates, click Windows Form, and then click Open. By default, a Windows Form that is named Form2 is created.
- Add a Button control to the Form2 form. By default, the Button1 Button control is added to the Form2 form.
- Right-click the Button1 Button control, and then click Properties.
- In the Properties window, set the Text property to Add Numbers.
- 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.
- Right-click the Label1 Label control, and then click Properties.
- In the Properties window, set the Size property to 200, 56.
- 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("Enter the first number")
secondnum = InputBox("Enter the second number")
result = firstnum + secondnum
MessageBox.Show("The sum of the two numbers is:" & result) back to the topWrite code to validate the Windows user in your Visual Basic .NET applicationYou 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: - In Solution Explorer, right-click Form1.vb, and then click View Code.
- 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 - Locate the following code:
End Class - 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 "advapi32.dll" (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("kernel32.dll")> _
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 "kernel32.dll" (ByVal handle As IntPtr) As Boolean
- Locate the following code:
End Class - 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("Failed to format message for error code " + errorCode.ToString() + ". ")
End If
Return lpMsgBuf
End Function - In Solution Explorer, right-click Form1.vb, and then click View Designer.
- 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 = "Add Numbers"
frm2.Label1.Text = "Click this button to add two numbers"
frm2.Show()
Else
frm2.Label1.Text = " You do not have administrative credentials."
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("Exception occurred. " + ex.Message)
End Try back to the topVerify that your Visual Basic .NET application worksTo verify that the validation has completed correctly, follow these steps: - On the Build menu, click Build Solution.
- On the Debug menu, click Start.
- In the TextBox1 box, type a user name.
- In the TextBox2 box, type a password.
- Click Validate User.
back to the topREFERENCESFor more information, visit the following Microsoft Developer Network (MSDN) Web sites: back to the top
Modification Type: | Minor | Last Reviewed: | 10/3/2006 |
---|
Keywords: | kbvs2005swept kbvs2005applies kbDevSecurity kbSecurity kbAuthentication kbUser kbpermissions kbpasswords kbWindowsForms kbcode kbHOWTOmaster kbhowto KB841699 kbAudDeveloper |
---|
|
|
©2004 Microsoft Corporation. All rights reserved.
|
|