Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

HOW TO: Create an IAuthenticationModule by Using Visual Basic .NET


View products that this article applies to.

Summary

This step-by-step article discusses how to use Visual Basic .NET to create an implementation of an IAuthenticationModule module that performs Basic authentication. This article describes how to create, deploy, configure, and then test the authentication module.

An authentication module is a component that a client uses to perform authentication with the server. Applications that use the WebResponse class rely on the authentication module.

Implement the IAuthenticationModule Interface

  1. Start Microsoft Visual Studio .NET.
  2. On the File menu, point to Add Project, and then click New Project.
  3. In the New Project dialog box, click Visual Basic Projects under Project Type.
  4. Under Templates, click Class Library, and then name your project MyAuthenticationModule.
  5. Add the following directives to the class:
    Imports System.Net
    Imports System.Text
    
  6. Rename the class MyAuthenticationModule.vb, and then change the class definition to reflect this change.
  7. Implement the IAuthenticationModule interface. Your class definition appears as follows:

    Public Class MyAuthenticationModule
    Implements IAuthenticationModule
  8. From the IAuthenticationModule interface, implement the following (with these returns, to keep it simple):
    • The Authenticate method
    • The PreAuthenticate property (return Nothing)
    • The AuthenticationType property
    • The CanPreAuthenticate property (return False)
  9. Use the following code for MyAuthenticationModule.vb:
    Imports System.Net
    Imports System.Text
    
    Public Class MyAuthenticationModule
       Implements IAuthenticationModule
    
        Private m_myAuthType As String = "Basic"
    
        Public Function Authenticate(ByVal challenge As String, ByVal request As WebRequest, ByVal credentials As ICredentials) As Authorization Implements IAuthenticationModule.Authenticate
    
            Dim myHttpWebRequest As HttpWebRequest = request
            Dim myIndex As Integer = challenge.ToLower().IndexOf(m_myAuthType.ToLower())
    
            If (-1 = myIndex) Then Return Nothing 'Basic authentication was not the MyChallenge.
    
            Dim myDomain As String = credentials.GetCredential(request.RequestUri, m_myAuthType).Domain
            Dim myUserName As String = credentials.GetCredential(request.RequestUri, m_myAuthType).UserName
            Dim myPassword As String = credentials.GetCredential(request.RequestUri, m_myAuthType).Password
    
            Debug.WriteLine("Authentication module is invoked for " & myDomain & "\" & myUserName)
    
            Dim myAuthBytes() As Byte = Encoding.ASCII.GetBytes(myDomain & "\" & myUserName & ":" & myPassword)
    
            Dim myAuthString As String = System.Convert.ToBase64String(myAuthBytes)
    
            Return New Authorization(m_myAuthType & " " & myAuthString, True, "myAuth")
    
        End Function
    
        Public ReadOnly Property AuthenticationType() As String Implements IAuthenticationModule.AuthenticationType
            Get
                Return m_myAuthType
            End Get
        End Property
    
        Public ReadOnly Property CanPreAuthenticate() As Boolean Implements IAuthenticationModule.CanPreAuthenticate
            Get
                Return False
            End Get
        End Property
    
        Public Function PreAuthenticate(ByVal request As WebRequest, ByVal credentials As ICredentials) As Authorization Implements IAuthenticationModule.PreAuthenticate
            Return Nothing
        End Function
    End Class
    
  10. Compile the project.

Create an Application to Test the Module

  1. Start Visual Studio .NET.
  2. On the File menu, point to Add Project, and then click New Project.
  3. In the New Project dialog box, click Visual Basic Projects under Project Type.
  4. Under Templates, click Console Application, and then name it AuthModuleTester.
  5. Rename the class AuthModuleTester.vb, and then change the class definition to AuthModuleTester.
  6. Use the following code for AuthModuleTester.vb:
    Imports System.IO
    Imports System.Net
    Imports System.Text
    
    Module AuthModuleTester
        Public Class AuthModuleTester
    
            Public Shared Sub Main(ByVal MyArgs() As String)
    
                Dim myRequest As HttpWebRequest = Nothing
    
                Try
                    myRequest = WebRequest.Create(CStr(MyArgs(0)))
    
                    Dim myDomain As String = "<Domain>"   'Give the Machine or Domain name
                    Dim myUserName As String = "<User>"     'Give the User name
                    Dim myPassword As String = "<Password>"   'Give the Password
    
                    myRequest.Credentials = New NetworkCredential(myUserName, myPassword, myDomain)
    
                Catch ex As Exception
                    Console.WriteLine("Exception " & ex.Message)
                End Try
    
                Dim myResponse As HttpWebResponse = Nothing
    
                Try
                    myResponse = CType(myRequest.GetResponse(), HttpWebResponse)
                Catch ex As Exception
                    Console.WriteLine("Exception " & ex.Message)
                End Try
    
                Dim myResponseStream As Stream = myResponse.GetResponseStream()
                Dim myOneByte As Integer = -1
                Dim myResponseText As New StringBuilder()
    
                If (True = myResponseStream.CanRead) Then
                    myOneByte = myResponseStream.ReadByte()
                    While (myOneByte <> -1)
                        myResponseText.Append(Convert.ToChar(myOneByte))
                        myOneByte = myResponseStream.ReadByte()
                    End While
                Else
                    Console.WriteLine("Unable to read from myResponse stream.")
                End If
    
                Console.WriteLine(myResponseText.ToString())
    
            End Sub
        End Class
    End Module
    
  7. Update the code in step 6 by using the following active user settings:
    • Replace <Domain> with your active domain name or computer name.
    • Replace <User> with the active user name on this computer.
    • Replace <Password> with the active user password on this computer.
  8. Right-click AuthModuleTester, and then click Properties. The AuthModuleTester Property Pages dialog box appears.
  9. In the Startup object box, select AuthModuleTester.AuthModuleTester.
  10. Compile the project.

Deploy the Module and Configure the System

  1. Copy the MyAuthenticationModule.dll assembly to the folder where the AuthModuleTester.exe assembly is located.
  2. Create a file named AuthModuleTester.exe.config in the same folder.
  3. Add the following code to AuthModuleTester.exe.config:
    <configuration>
      <system.net>
        <authenticationModules>
          <remove type="System.Net.BasicClient" />
          <add type="MyAuthenticationModule.MyAuthenticationModule, MyAuthenticationModule" />		
        </authenticationModules>
      </system.net>
    </configuration>
    
By using this configuration, you can use your module to authenticate Basic authentication challenges from a Web server. The .NET Framework includes authentication modules that support Basic, NTLM, Kerberos, Negotiate, and Digest authentication. For your module to be called upon for Basic (instead of .NET) authentication, the
remove type="System.Net.BasicClient" /
line removes System.Net.BasicClient from the authenticationModules list. Keep this configuration only during the testing of your module.

Test the Module

  1. Create an ASP.NET page named Page1.aspx, and then put it in a Microsoft Internet Information Services (IIS) application. Add the following code to the application:
    <% Response.Write("Hello " & Context.User.Identity.Name) %>
    Note To paste the code in the Visual Studio .NET Editor, click Edit, and then click Paste as HTML.
  2. To secure the page by using only Basic authentication, follow these steps:
    1. Click Start, point to Programs, point to Administrative tools, and then click Internet Information Services.
    2. Expand Web Sites.
    3. Locate your ASP.NET application folder, and then click Page1.aspx.
    4. Right-click Page1.aspx, and then click Properties.
    5. In Properties, click the File Security tab.
    6. Under Anonymous access and authentication control, click edit.
    7. In the Authentication Methods dialog box, click to select the Basic authentication check box under Authenticated access.
    8. Click to clear all other check boxes, and then click OK.
  3. Run the AuthModuleTester.exe application at the command line, and then pass the URL as argument. For example:
    AuthModuleTester "http://IIS Server Name/Web Folder/page1.aspx"
    You receive the following results:
    Hello domain\user

↑ Back to the top


References

For more information, see the following topics in the Microsoft .NET Framework Software Development Kit (SDK) documentation:

↑ Back to the top


Keywords: KB331501, kbhowtomaster, kbsecurity, kbauthentication, kbwebforms

↑ Back to the top

Article Info
Article ID : 331501
Revision : 9
Created on : 4/19/2007
Published on : 4/19/2007
Exists online : False
Views : 454