Secure Your Microsoft .NET Client

Before you add security to your clients, follow the steps in Checklist: Configure Authentication and Authorization to set up security on Kaazing Gateway for your client. The authentication and authorization methods configured on the Gateway influence your client's security implementation. For information on secure network connections between clients and the Gateway, see Checklist: Secure Network Traffic with the Gateway.

Before You Begin

This procedure is part of Checklist: Build Microsoft .NET WebSocket Clients.

Note: Learn about supported browsers, operating systems, and platform versions in the Release Notes.

To Secure Your Microsoft .NET Client

This section contains the following topics:

Authenticating your client involves implementing a challenge handler to respond to authentication challenges from the Gateway. If your challenge handler is responsible for obtaining user credentials, then you will also need to implement a login handler. For more information, see the .NET Client API.

Creating a Basic Challenge Handler

A challenge handler is a constructor used in an application to respond to authentication challenges from the Gateway when the application attempts to access a protected resource. Each of the resources protected by the Gateway is configured with a different authentication scheme (for example, Basic, Application Basic, Application Negotiate, or Application Token), and your application requires a challenge handler for each of the schemes that it will encounter or a single challenge handler that will respond to all challenges. Also, you can add a dispatch challenge handler to route challenges to specific challenge handlers according to the URI of the requested resource.

For information about each authentication scheme type, see Configure the HTTP Challenge Scheme.

Clients with a single challenge handling strategy for all 401 challenges can simply set a specific challenge handler as the default using ChallengeHandlers.Default. The following is an example of how to implement a single challenge handler for all challenges. This example uses the code from the Kaazing .NET WebSocket Echo tutorial desktop application (https://github.com/kaazing/dotnet.client.tutorials/blob/develop/ws/WindowsDesktop/MainForm.cs#L52):

 
private WebSocket webSocket = null;
private WebSocketFactory factory = new WebSocketFactory();
...
private void ConnectButton_Click(object sender, EventArgs e)
{
    // Immediately disable the connect button
    ConnectButton.Enabled = false;
    LocationText.Enabled = false;

    //setup ChallengeHandler to handler Basic/Application Basic authentications
    BasicChallengeHandler basicHandler = BasicChallengeHandler.Create();
    basicHandler.LoginHandler = new LoginHandlerDemo(this);

    factory.ChallengeHandler = basicHandler;
    webSocket = factory.CreateWebSocket();
    Log("CONNECT:" + LocationText.Text);

    webSocket.OpenEvent += new OpenEventHandler(OpenHandler);
    webSocket.CloseEvent += new CloseEventHandler(CloseHandler);
    webSocket.MessageEvent += new MessageEventHandler(MessageHandler);

    webSocket.Connect(LocationText.Text);
}

The following example shows how to implement a login handler in your .NET client.

First, create a login form that a user can use to submit their credentials. Here is an example from the Kaazing .NET WebSocket Echo tutorial desktop application: https://github.com/kaazing/dotnet.client.tutorials/blob/develop/ws/WindowsDesktop/LoginDemoForm.Designer.cs.

Next, add the code for the login form. This code is taken from https://github.com/kaazing/dotnet.client.tutorials/blob/develop/ws/WindowsDesktop/LoginDemoForm.cs.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using Kaazing.Security;

namespace EchoDemo
{
    public partial class LoginDemoForm : Form
    {

        public string Username
        {
            get { return UsernameText.Text; }
        }

        public string Password
        {
            get { return PasswordText.Text; }
        }

        public LoginDemoForm()
        {
            InitializeComponent();
        }

    }
}

Add the code to handle the login form and the submitted user credentials and return this information to the main application code. This code is taken from https://github.com/kaazing/dotnet.client.tutorials/blob/develop/ws/WindowsDesktop/LoginHandlerDemo.cs.

using System;
using Kaazing.Security;

namespace EchoDemo
{
    ///
    /// Challenge handler for Basic authentication. See RFC 2617.
    ///
    public class LoginHandlerDemo : LoginHandler
    {
        private MainForm parent;
        /// 
        /// constructor
        /// pass in main form for callback
        /// 
        /// 
        public LoginHandlerDemo(MainForm form)
        {
            this.parent = form;
        }

        #region LoginHandler Members

        PasswordAuthentication LoginHandler.GetCredentials()
        {
            return parent.AuthenticationHandler();
        }

        #endregion
    }
}

Lastly, in the main code for your application, add an event handler for managing login password authentication. This code will call the login form code and use the credentials returned from that form to send to the Gateway for authentication. This code is taken from: https://github.com/kaazing/dotnet.client.tutorials/blob/develop/ws/WindowsDesktop/MainForm.cs#L126.

/// Handle server authentication challenge request,
/// Popup a login window for username/password
///
public PasswordAuthentication AuthenticationHandler()
{
    PasswordAuthentication credentials = null;
    AutoResetEvent userInputCompleted = new AutoResetEvent(false);
    this.BeginInvoke((InvokeDelegate)(() =>
    {
        LoginDemoForm loginForm = new LoginDemoForm();
        if (loginForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            credentials = new PasswordAuthentication(loginForm.Username, loginForm.Password.ToCharArray());
        }
        userInputCompleted.Set();
    }));
    // wait user click 'OK' or 'Cancel' on login window
    userInputCompleted.WaitOne();
    return credentials;
}

Managing Log In Attempts

When it is not possible for the Gateway client to create a challenge response, the client must return null to the Gateway to stop the Gateway from continuing to issue authentication challenges.

The following .NET example demonstrates how to stop the Gateway from issuing further challenges.

public delegate void InvokeDelegate();

private const int maxRetries = 2;    // max retry number on wrong credentials
private int retry = 0;               // number of retry

/// <summary>
/// .Net HTML5 Demo Form
/// </summary>

public PasswordAuthentication AuthenticationHandler()
{
  PasswordAuthentication credentials = null;
  if (retry++ >= maxRetries)
  {
    return null;          // stop authentication when max retries reached
  }
  AutoResetEvent userInputCompleted = new AutoResetEvent(false);
  this.BeginInvoke((InvokeDelegate)(() =>
  {
    {
      credentials = new PasswordAuthentication(loginForm.Username, loginForm.Password.ToCharArray());
    }
    else
    {
      //user click cancel button to stop the authentication
      retry = 0;     // reset retry counter
      credentials = null;  // return null to stop authentication process
    }
    userInputCompleted.Set();
  }));
  // wait user click 'OK' or 'Cancel' on login window
  this.BeginInvoke((InvokeDelegate)(() =>
  {
    Log("CONNECTED");

    retry = 0;     // reset retry counter
    DisconnectButton.Enabled = true;
    SendButton.Enabled = true;
  }));
  {
    Log("DISCONNECTED");

    retry = 0;     // reset retry counter
    ConnectButton.Enabled = true;
    DisconnectButton.Enabled = false;
    SendButton.Enabled = false;

Negotiate and Register a Location-Specific Challenge Handler

Client applications with location-specific challenge handling strategies can register a DispatchChallengeHandler object, on which location-specific ChallengeHandler objects are then registered. The result is that whenever a request matching one of the specific locations encounters a 401 challenge from the server, the corresponding ChallengeHandler object is invoked to handle the challenge.

The following example creates a challenge handler to handle authentications and uses DispatchChallengeHandler to assign different challenge handler to each location:

dispatchHandler = 
        ChallengeHandlers.Load<DispatchChallengeHandler>(typeof(DispatchChallengeHandler));

ChallengeHandlers.Default = dispatchHandler;

LoginHandler loginHandler = new LoginHandlerDemo(this);

Next, set a loginHandler for this location:

BasicChallengeHandler basicHandler = 
        ChallengeHandlers.Load<BasicChallengeHandler>(typeof(BasicChallengeHandler));

basicHandler.LoginHandler = loginHandler;

dispatchHandler.Register("ws://myserver.com/*", basicHandler);

Add another challenge handler for a second location:

BasicChallengeHandler basicHandler2 = 
        ChallengeHandlers.Load<BasicChallengeHandler>(typeof(BasicChallengeHandler));

basicHandler2.LoginHandler = loginHandler2;

dispatchHandler.Register("ws://otherserver.com/*", basicHandler2);

Using Wildcards to Match Sub-domains and Paths

You can use wildcards (“*”) when registering locations using DispatchChallengeHandler. Some examples of locationDescription values with wildcards are:

See Also

.NET and Silverlight Client API