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 C# .NET


View products that this article applies to.

Summary

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

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

Implement the IAuthenticationModule Interface

  1. Open Microsoft Visual Studio .NET. In Visual C# .NET, create a new Class Library project named MyAuthenticationModule.
  2. Add the following directives to the class:
    using System.Net;
    using System.Text;
    					
  3. Rename the class to MyAuthenticationModule.cs, and then change the class definition to reflect this change.
  4. Implement the IAuthenticationModule interface. Your class definition should appear as follows:
    public class MyAuthenticationModule : IAuthenticationModule
    					
  5. From the IAuthenticationModule interface, implement the following (with these returns, to keep it simple):
    • The Authenticate method
    • The PreAuthenticate property (return Null)
    • The AuthenticationType property
    • The CanPreAuthenticate property (return False)
  6. Code for MyAuthenticationModule.cs
    using System;
    using System.Net;
    using System.Text;
    
    namespace MyAuthenticationModule
    {
      public class MyAuthenticationModule : IAuthenticationModule
      {
        private string _authType = "Basic";
    
        public Authorization Authenticate(String challenge, WebRequest request, ICredentials credentials)
        {
          HttpWebRequest httpWebRequest = request as HttpWebRequest;
    			
          int index = challenge.ToLower().IndexOf(_authType.ToLower());
          if(-1 == index)//Basic authetication was not the challenge.
          {return null;}
    
          String domain = credentials.GetCredential(request.RequestUri, _authType).Domain;
          String username = credentials.GetCredential(request.RequestUri, _authType).UserName;
          String password = credentials.GetCredential(request.RequestUri, _authType).Password;
        
    
    
          byte[] authBytes = System.Text.Encoding.ASCII.GetBytes(domain + "\\" + username + ":" + password);
          String authString = Convert.ToBase64String(authBytes);
    
          return new Authorization(_authType + " " + authString, true, "myAuth");
        }
    
        public Authorization PreAuthenticate(WebRequest request, ICredentials credentials)
        {return null;}
    
        public String AuthenticationType
        {get{return _authType;}}
    
        public bool CanPreAuthenticate
        {get{return false;}}		 
      }
    }
    					
  7. Compile the project.

Create an Application to Test the Module

  1. In Visual Studio .NET, on the File menu, click Add Project, and then click New Project.
  2. In the New Project dialog box, click Console Application project under Project Type, and then name it AuthModuleTester.
  3. Add the following directives to the class:
    using System.IO;
    using System.Net;
    using System.Text;
    					
  4. Rename the class to AuthModuleTester.cs, and then change the class definition to reflect this.
  5. Code for AuthModuleTester.cs:
    using System;
    using System.IO;
    using System.Net;
    using System.Text;
    
    namespace AuthModuleTester
    {
      class AuthModuleTester
      {
        static void Main(string[] args)
        {
          HttpWebRequest request = null;
          try
          {
            request = WebRequest.Create(args[0]) as HttpWebRequest;
            String domain = "<domain>";
    	String username = "<username>";
    	String password = "<password>";
    	request.Credentials = new NetworkCredential(username, password, domain);
          }
          catch(Exception ex)
          {
            Console.WriteLine("Exception " + ex.Message);
            return;
          }
    
          HttpWebResponse response = null;
    
          try
          {
            response = request.GetResponse() as HttpWebResponse;
          }
          catch(Exception ex)
          {
            Console.WriteLine("Exception " + ex.Message);
            return;
          }
    
          Stream responseStream = response.GetResponseStream();
    			
          int oneByte = -1;
    
          StringBuilder responseText = new StringBuilder();
          if(true == responseStream.CanRead)
          {
            while(-1 != (oneByte = responseStream.ReadByte()))
            {
              responseText.Append((char)oneByte);
            }
          }
          else
          {
            Console.WriteLine("Unable to read from response stream.");
            return;
          }
    
          Console.WriteLine(responseText.ToString());
        }		
      }
    }
    					
  6. Compile the project.

Deploy the Module and Configure the System

  1. Copy the MyAuthenticationModule.dll assembly to the directory where the AuthModuleTester.exe assembly is located.
  2. Create a file named AuthModuleTester.exe.config in the same directory.
  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>
    						
    With this configuration, your module can be used to authenticate Basic authentication challenges from a Web server. The .NET Framework includes authentication modules that support Basic, NTLM, Kerberos, Negotiate, and Digest authentication. In order 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 an IIS application with the following code:
    <% Response.Write("Hello " + Context.User.Identity.Name); %>
    					
  2. Secure the page with only Basic authentication.
  3. Run the AuthModuleTester.exe application at the command line, and then pass in the URL to Page1.aspx.
  4. If the active debugger window is present, you will see a string generated by the authentication module.
You can expect to receive the following results:
Hello <domain>\<user>
				

↑ Back to the top


Keywords: KB318786, kbsecurity, kbhowtomaster

↑ Back to the top

Article Info
Article ID : 318786
Revision : 11
Created on : 7/11/2005
Published on : 7/11/2005
Exists online : False
Views : 459