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

Article translations Article translations
Article ID: 841699 - View products that this article applies to.
Expand all | Collapse all

On This Page

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.

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.

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)

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.
  4. Under Templates, click Windows Application.
  5. In the Name box, type MyApp, and then click OK. By default, a Windows Form that is named Form1 is created.

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:
  1. On the View menu, click Toolbox.
  2. 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.
  3. 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.
  4. Right-click the TextBox2 TextBox control, and then click Properties.
  5. In the Properties window, set the PasswordChar property to *.
  6. 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.
  7. Right-click the Button1 Button control, and then click Properties.
  8. In the Properties window, set the Text property to Validate User.
  9. In Solution Explorer, right-click MyApp, point to Add, and then click Add New Item. The Add New Item - MyApp dialog box appears.
  10. Under Templates, click Windows Form, and then click Open. By default, a Windows Form that is named Form2 is created.
  11. Add a Button control to the Form2 form. By default, the Button1 Button control is added to the Form2 form.
  12. Right-click the Button1 Button control, and then click Properties.
  13. In the Properties window, set the Text property to Add Numbers.
  14. 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.
  15. Right-click the Label1 Label control, and then click Properties.
  16. In the Properties window, set the Size property to 200, 56.
  17. 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)

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:
  1. In Solution Explorer, right-click Form1.vb, and then click View Code.
  2. 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
  3. Locate the following code:
    End Class
  4. 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
    
  5. Locate the following code:
    End Class
  6. 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
  7. In Solution Explorer, right-click Form1.vb, and then click View Designer.
  8. 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

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.

REFERENCES

For more information, visit the following Microsoft Developer Network (MSDN) Web sites:
LogonUser
http://msdn2.microsoft.com/en-us/library/aa378184.aspx

DllImportAttribute class
http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute(vs.71).aspx

Declare statement
http://msdn2.microsoft.com/en-us/library/4zey12w5(vs.71).aspx

CloseHandle
http://msdn2.microsoft.com/en-us/library/ms724211.aspx

WindowsIdentity class
http://msdn2.microsoft.com/en-us/library/system.security.principal.windowsidentity(vs.71).aspx

Properties

Article ID: 841699 - Last Review: May 18, 2007 - Revision: 2.9
APPLIES TO
  • Microsoft Visual Basic 2005
  • Microsoft Visual Basic .NET 2003 Standard Edition
  • Microsoft Visual Basic .NET 2002 Standard Edition
Keywords: 
kbvs2005swept kbvs2005applies kbdevsecurity kbsecurity kbauthentication kbuser kbpermissions kbpasswords kbwindowsforms kbcode kbhowtomaster kbhowto KB841699

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com