Securing Silverlight Applications

In this lesson of the Silverlight tutorial, you will learn...
  1. About software security principles
  2. Security principles that apply to Silverlight
  3. To authenticate a user in a Silverlight application

This lesson will introduce software security principles and illustrate a practical example of authenticating a user in a Silverlight application.

Software Security Basics

Data is pretty much at the heart of all business software. Data pertaining to identification is a foundation of ecommerce. In ecommerce and business today, a business must be able to trust data related to a user and the user's identity. As such, identity theft is growing to be one of the top crimes perpetrated. With that said, the need to protect data managed by software is of prime importance and should be considered in the conceptual and logical software design phases. In fact, a formal security plan should be compiled that includes a plan for determining a user's identity, what tasks a user is allowed to perform in an application, and how data is to be secured while being transported and stored.

When discussing software security, all applications typically perform the two "A" words, authentication and authorization. Authentication is the process of determining a user's identity. A user's identity is generally determined by using user credentials such as a username and a password. Once a user's identity is determined, an application must determine what a user has permission to perform. Authorization is the process of determining a user's permissions within an application.

The method used to secure data that is being transported and stored varies based on the type of application being created. For instance, a Windows application that is not exposed to the Web can rely on internal network security to protect data whereas a Web application must take many precautions to guard against malicious attacks.

In a Web application environment, data is transported from a client's computer, over the Web, to a Web server. A client computer that accesses a Web application may be comprised of any operating system and any Web browser, thus it is nearly impossible to impose strict security mechanisms on the client's computer in a traditional Web application. Data entered on a client's computer is generally already known to the user that is entering it, hence, securing data while it is on the client's computer really isn't a significant concern. However, once data is leaves a client's computer and is transported over the Web to the Web server, it can be intercepted by anyone using an HTTP packet sniffer or other similar mechanism.

In order to secure data while it is transported over the Web, the data is encrypted before it leaves the client machine and unencrypted when it reaches the Web server and visa versa. There are many methods used in the software industry to encrypt data, however, the standard used on the Web for ecommerce is called Secure Sockets Layer (SSL) and utilizes 128-bit encryption. SSL is implemented through certificates that can be obtained from a third party certificate authority (CA) such as Verisign.

Web Service Security

A Web service is a class that is available over the Web. A Web service contains methods that are exposed over the Web to be called by any type of client application. In many scenarios, a Web method will provide access to a server database so that a client application can retrieve data. With that in mind, standards had to be put into place so that calls made to Web methods could be authenticated prior to execution; in essence, securing the Web service.

Web service standards, just as all other Web standards, are constantly evolving to keep up with technological advances. Maintaining a secure environment over the Web is not an easy task. To add to the complexity, bear in mind that the Web is a stateless environment. Communications between Web clients and Web methods are handled in the same manner as communications between Web clients and Web sites. Each request is isolated from all other requests. A method of maintaining state between requests to a Web method is necessary so that a client does not have to be authenticated with each request.

In the simplest example, user credentials can be passed to a Web method with each request so that the request can be authenticated. However, formal standards have been created for authenticating user requests to Web methods. In a nutshell, the default mechanism used to transport data to and from a Web method, SOAP, is constructed just very similar to an HTML document. The SOAP document is referred to an envelope and it includes a head section and a body section. The head section is optional but can be used to transport additional information and parameters that are intended to be utilized by the processing engine. When information is transported in the SOAP header, the SOAP message is said to contain a "custom SOAP header". User credentials is one example of information that can be passed in a custom SOAP header.

Silverlight Security

Silverlight applications execute entirely on the client machine with occasional calls being made to a service that resides on a Web server. With that in mind, you may want to authenticate a user to use a Silverlight application simply as a feature of the application and to protect data displayed. For instance, you may create a Silverlight application that allows a user to manage their finances. An application of this type would, obviously, benefit from user authentication.

Additionally, a Silverlight application may make calls to a service residing on a Web server in order to retrieve data on the server. At this point, the service that resides on the server should be secured as to authenticate users making calls to the service.

Aside from making remote calls to a Web method, all Silverlight code executes within a secure environment that is isolated from the host operating system somewhat. This environment is referred to as the "sandbox". The Silverlight version of the .NET Framework is powerful but due to the security constraints placed on code executing in the Silverlight sandbox, tasks that can be performed by using the Silverlight version of the .NET Framework are limited in comparison to the full .NET Framework.

Silverlight Services

The entire discussion of Web application security must take a detour at this point. Remember that Silverlight applications are only capable of making calls to Web services that reside in the same domain as the Silverlight application and data can only be transported to a Web service from a Silverlight application using JSON. The cross-domain call restriction only serves to further reinforce the security of Silverlight data communications. However, securing data being transported using JSON requires different action than using custom SOAP headers.

The basic premise behind authenticating a user request to a Web method is to include user credentials in the request. As mentioned, when a Web method transports data by using SOAP, the user credentials are stored in the SOAP header. When a service only transports data by using JSON, user credentials can be passed as additional parameters to a Web method.

Securing Silverlight Example

With the lack of user management facilities in Silverlight, we are left to perform user management and security functionality using other facilities. As we've already illustrated, Silverlight is an extension to ASP.NET AJAX and meshes very well with it. ASP.NET AJAX includes facilities to manage users and security. However, the AJAX facilities only offer limited functionality. We also have the option of managing users programmatically using custom code.

As an example, we can take the data access solution created in the previous lab and incorporate user authentication at two levels: upon the user attempting to display a page containing Silverlight content and upon a call being made to the Web method. At the completion of the pet information example, the example illustrated a Silverlight application making a call to a Web service that resides in an ASP.NET Futures Web site as shown in the figure below.

The first step in the process is to modify the Web service so that it includes a method for authenticating a user, given a username and password. In this example, we'll simply perform a string comparison, however, in a real world scenario, user information would be stored in a database table or even Active Directory. Furthermore, in a real world scenario, when user credentials are being transported to a Web server, the messages should be encrypted by using SSL. The Web method used to authenticate users is shown in the code snippet below.

    [WebMethod]
    public bool AuthenticateUser(string username, string password)
    {

      if (username == "shannon" & password == "letmein")
      {

        return true;
      }
      else {

        return false;
      }
    }

The next step is to create a class to hold user information. User information could just be kept in global variables but is much easier to keep track of and better designed by being kept inside a class. The class used to manage user information in this example is shown below.

Code Sample: SecuringSilverlightApplications/Demos/PetInformationClientLINQ/PISCLINQ/Page.xaml.cs

using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace PISCLINQ
{
  public partial class Page : Canvas
  {

    UserInformation user = new UserInformation();

    public void Page_Loaded(object o, EventArgs e)
    {
      // Required to initialize variables
      InitializeComponent();

      CheckUserStatus();
    }

    public void GetPetInfo(object o, MouseEventArgs e)
    {

      PISCLINQ.localhost.PetService svc = new PISCLINQ.localhost.PetService();
      IEnumerable<string> pets = from petInfo in svc.GetPetInfo(user.UserName, user.Password)
                                select petInfo;

      // Display the results.
      foreach (string pet in pets)
      {

        tbOutput.Text += pet;
      }
    }

    public void LogUserInOut(object o, MouseEventArgs e) {

      if (!user.LoggedIn)
      {

        // Due to the lack of data entry controls, for simplicity sake, we'll
        // provide the user values directly here.
        user.UserName = "shannon";
        user.Password = "letmein";
        user.Login();
      }
      else {

        user.LoggedIn = false;
      }
      CheckUserStatus();
    }

    public void CheckUserStatus() {

      // Is the user logged in?
      if (!user.LoggedIn)
      {

        tbLogin.Text = "Login";
        canvasGetPetInfo.Visibility = Visibility.Collapsed;
        tbOutput.Text = "";
      }
      else
      {

        tbLogin.Text = "Logout";
        canvasGetPetInfo.Visibility = Visibility.Visible;
      }
    }
  }
}

Now some code is required in the XAML and the code behind file to respond to the new functionality. The XAML has been redesigned to include a login and logout button. In a real world scenario, we'd collect the username and password from the user and respond to invalid login attempts. Due to the lack of data entry controls, to simplify things here, we'll simply hard code the username and password. The updated XAML is shown in the markup listing below.

Code Sample: SecuringSilverlightApplications/Demos/PetInformationClientLINQ/PISCLINQ/Page.xaml

  
<Canvas
        xmlns="http://schemas.microsoft.com/client/2007"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="parentCanvas"
        Loaded="Page_Loaded"
        x:Class="PISCLINQ.Page;assembly=ClientBin/PISCLINQ.dll"
        Width="560"
        Height="320"
        >

  <Canvas.Background>
    <LinearGradientBrush EndPoint="0.498,-0.375" StartPoint="0.502,1.375">
      <GradientStop Color="#FFFFFFFF" Offset="0"/>
      <GradientStop Color="#FFA3A535" Offset="1"/>
    </LinearGradientBrush>
  </Canvas.Background>
  <Path Width="513" Height="1" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" StrokeThickness="0.5" Canvas.Left="23.5" Canvas.Top="39.5" Data="M24,40 L536,40"/>

  <TextBlock Width="512" Height="232" Canvas.Left="24" Canvas.Top="56" TextWrapping="Wrap">
    <Run FontFamily="Segoe UI" FontSize="12" FontWeight="Normal" x:Name="tbOutput"/>
  </TextBlock>
  <Canvas Cursor="Hand" Width="178" Height="24.5" Canvas.Left="23.5" Canvas.Top="11.5" x:Name="canvasGetPetInfo" MouseLeftButtonUp="GetPetInfo">
    <Rectangle Width="168.5" Height="24" Stroke="#FFD4A524" StrokeThickness="1" RadiusX="4" RadiusY="4">
      <Rectangle.Fill>
        <LinearGradientBrush EndPoint="0.505,4.01" StartPoint="0.495,-3.01">
          <GradientStop Color="#FF000000" Offset="0.301"/>
          <GradientStop Color="#00FFFFFF" Offset="0.737"/>
        </LinearGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Width="168.5" Height="24" TextWrapping="Wrap" Canvas.Left="9.5" Canvas.Top="0.5">
      <Run FontFamily="Segoe UI" FontSize="16" Text="Get Pet Information"/>
    </TextBlock>
  </Canvas>

  <Canvas x:Name="canvasLogin" Width="178" Height="24.5" Canvas.Left="367.5" Canvas.Top="11.5" Cursor="Hand" MouseLeftButtonUp="LogUserInOut">
    <Rectangle Width="168.5" Height="24" Stroke="#FFD4A524" StrokeThickness="1" RadiusX="4" RadiusY="4">
      <Rectangle.Fill>
        <LinearGradientBrush EndPoint="0.505,4.01" StartPoint="0.495,-3.01">
          <GradientStop Color="#FF000000" Offset="0.301"/>
          <GradientStop Color="#00FFFFFF" Offset="0.737"/>
        </LinearGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Width="168.5" Height="24" TextWrapping="Wrap" Canvas.Left="9.5" Canvas.Top="0.5" Text="Login" x:Name="tbLogin"/>
  </Canvas>

</Canvas>

The resulting page now resembles the figure below.

When the user clicks the Login button, a new event handler is fired in the code behind that handles page events.

The page resembles the following figure when the user clicks the Login button.

The next step is to modify the Web method so that it authorizes user credentials before executing the method. The updated Web method code is shown in the snippet below. Again, this is a simplified example. In a real world example, user credentials would be validated against the user data store and invalid execution attempts would be handled.

    public List<string> GetPetInfo(string username, string password)
    {

        List<string> petInfo = new List<string>();

      // user information would generally be validated here against the user
      // data store.
      if (username == "shannon" & password == "letmein")
      {

        PetClassesDataContext petsDB = new PetClassesDataContext();

        var pets = from pet in petsDB.Pets
                   select pet;

        foreach (var pet in pets)
        {

          petInfo.Add("My pet is named " + pet.Name + ". It is a " +
(pet.Gender == true ? "male" : "female") + " " + pet.Breed + " that weighs " +
pet.Weight + " pounds. " + pet.Notes + " ");
        }

      }
      return petInfo;
    }

Finally, the code that calls the updated Web method must also be modified so that it passes the user credentials. The updated code is shown below.

    public void GetPetInfo(object o, MouseEventArgs e)
    {

      PISCLINQ.localhost.PetService svc = new PISCLINQ.localhost.PetService();
      IEnumerable<string> pets = from petInfo in
svc.GetPetInfo(user.UserName, user.Password)
                                select petInfo;

      // Display the results.
      foreach (string pet in pets)
      {

        tbOutput.Text += pet;
      }
    }

The resulting page displayed after the user clicks the Get Pet Information button is shown in the figure below.

Silverlight Enterprise Security Features

A common question asked is where are the enterprise-level security features in Silverlight. The answer is that Microsoft has not yet included more advanced user management and security features in Silverlight but intends to include the features in future release.

Lab: Authenticating and Authorizing Users

In this lab, you will modify the lab from the previous module that created a simulated weather forecast control. You'll add user authentication functionality to the lab.

Securing Silverlight Applications Conclusion

In this lesson of the Silverlight tutorial, you

  • Reviewed software security principles
  • Authenticated a user in a Silverlight application
To continue to learn Silverlight go to the top of this page and click on the next lesson in this Silverlight Tutorial's Table of Contents.

Use of this website implies agreement to the following:

Copyright Information

All pages and graphics on this Web site are the property of Webucator, Inc. unless otherwise specified.

None of the content on this website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of web pages

This content may not be printed or saved. It is for online use only.


Linking to this website

You may link to any of the pages on this website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

This website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).

For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm.