tsJensen

A quest for software excellence...

Silverlight 3 and .NET RIA Services Forms Security

I finally carved out some time to experiment with Silverlight 3 and .NET RIA Services over the weekend. Specifically I wanted to experiment with Forms security and how one might secure a Silverlight "page" as well as the services on the server side along with a custom membership, role and profile providers. Here's the result.

Tools
Before you follow along on your own machine, be sure that you have these:

1. Visual Studio 2008 Pro (Visual Studio 2008 Professional Edition (90-day Trial))

2. Visual Studio 2008 SP1 (Microsoft Visual Studio 2008 Service Pack 1 (Installer))

3. Silverlight SDK (Microsoft® Silverlight™ 3 Tools for Visual Studio 2008 SP1)

4. RIA Services July 2009 Preview (Microsoft .NET RIA Services July 2009 Preview)

5. Download code for this post (download DemoAgRia.zip 427KB).

Once you have the tools installed, you can start a new Visual Studio project from the Silverlight projects types called Silverlight Business Application. Name yours whatever you like. I've chosen DemoAgRia.

s1

The project template creates a Silverlight and ASP.NET Web Application project and populates them with a number of helpful artifacts to get us started. There are two DomainService classes, one for authentication and one for user registration. These services use the standard ASP.NET Membership, Role and Profile provider model.

s2

You also get several "views" or Page and ChildWindow XAML controls with code-behind. These files are a familiar construct to any classic ASP.NET developer. Of course XAML is a whole new ballgame compared to the hodge podge of HTML. But rather than focus on these page and child window objects, I will focus this post on the security aspects of the app.

While the project template sets authentication to "Forms" based authentication there are no membership, role, or profile providers configured in the web.config. Since I'm going to create some custom providers in order to just experiment with the mechanics of security within the Silverlight and the web app, I'll just spin up some stub providers. Here's the web.config sections (including the "Forms" authentication node) for them:

<authentication mode="Forms"/>

<roleManager enabled="true" defaultProvider="AgRoleProvider">
  <providers>
    <clear />
    <add name="AgRoleProvider" type="DemoAgRia.Web.AgRoleProvider" />
  </providers>
</roleManager>
<membership defaultProvider="AgMembershipProvider">
  <providers>
    <clear />
    <add name="AgMembershipProvider" type="DemoAgRia.Web.AgMembershipProvider" />
  </providers>
</membership>
<profile enabled="true" defaultProvider="AgProfileProvider">
  <providers>
    <clear />
    <add name="AgProfileProvider" type="DemoAgRia.Web.AgProfileProvider" />
  </providers>
  <properties>
    <clear />
    <add name="PhoneNumber" />
    <add name="FullName" />
  </properties>
</profile>

Now I stub out the provider classes in the Providers folder of the web application. I won't post the code here because the implementation provides dumb data or place holders. Of course, a real set of providers, whether you use the AspSqlMembership provider or role your own, will do real authentication and provide real role and profile access. The stub membership class will authenticate any username and password to allow us to just play with the happy path for now.

Note the custom properties I've added to the profile provider above. These require some custom code in two places. First, in the profile provider class and then in the User class found in the AuthenticationService.cs file. Here's the code for both:

in AgProfileProvider.cs:

public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, 
  SettingsPropertyCollection collection)
{
  string userName = context["UserName"].ToString(); //use this to look up real values for user

  SettingsPropertyValueCollection s = new SettingsPropertyValueCollection();
  foreach (SettingsProperty p in collection)
  {
    if (p.Name == "PhoneNumber") s.Add(new SettingsPropertyValue(p) { PropertyValue = "508.555.1212" });
    if (p.Name == "FullName") s.Add(new SettingsPropertyValue(p) { PropertyValue = "Tyler Jensen" });
    //NOTE: replace with real lookups
  }
  return s;
}
in AuthenticationService.cs:

public class User : UserBase
{
  // NOTE: Profile properties can be added for use in Silverlight application.
  // To enable profiles, edit the appropriate section of web.config file.

  // public string MyProfileProperty { get; set; }
  public string FullName { get; set; }
  public string PhoneNumber { get; set; }
}

Now to use these new profile provider properties, let's modify some XAML in the LoginControl.xaml file so that rather than seeing the username of the logged in user, we'll see the FullName and the PhoneNumber.

Here's the existing XAML which we will modify:

<StackPanel x:Name="logoutControls" Style="{StaticResource LoginPanelStyle}">
  <TextBlock Text="welcome " Style="{StaticResource WelcomeTextStyle}"/>
  <TextBlock Text="{Binding Path=User.Name}" Style="{StaticResource WelcomeTextStyle}"/>
  <TextBlock Text="  |  " Style="{StaticResource SpacerStyle}"/>
  <Button x:Name="logoutButton" Content="logout" Click="LogoutButton_Click" Style="{StaticResource LoginRegisterLinkStyle}" />  
</StackPanel>

We now modify this XAML snippet to this:

 
<StackPanel x:Name="logoutControls" Style="{StaticResource LoginPanelStyle}">
  <TextBlock Text="welcome " Style="{StaticResource WelcomeTextStyle}"/>
  <TextBlock Text="{Binding Path=User.FullName}" Style="{StaticResource WelcomeTextStyle}"/>
  <TextBlock Text="  |  phone: " Style="{StaticResource SpacerStyle}"/>
  <TextBlock Text="{Binding Path=User.PhoneNumber}" Style="{StaticResource WelcomeTextStyle}"/>
  <TextBlock Text="  |  " Style="{StaticResource SpacerStyle}"/>
  <Button x:Name="logoutButton" Content="logout" Click="LogoutButton_Click" Style="{StaticResource LoginRegisterLinkStyle}" />
</StackPanel>

Now lets add a DomainService for fecthing some data. Right click on the web application's Services folder and select Add | New Item.

s3

Of course, we don't have a data or object context class, so we don't have any to choose from in the dialog.

s4

Leave "Enable client access" checked. We want a proxy class to automatically be generated from our service class on the server side. Just click OK and let's create our own custom DomainService.

Now you'll see something like this:

 
namespace DemoAgRia.Web.Services
{
  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.ComponentModel.DataAnnotations;
  using System.Linq;
  using System.Web.Ria;
  using System.Web.Ria.Data;
  using System.Web.DomainServices;


  // TODO: Create methods containing your application logic.
  [EnableClientAccess()]
  public class DemoDataService : DomainService
  {
  }
}

I'll put it into the root of the namespace by lopping off the ".Services" in the namespace declaration. This is just a convenience to me. You can do with it what you like.

Now let's add a couple of simplistic methods. Be sure to decorate them with the ServiceOperation attribute or the build process will not autogenerate the DemoDataContext class and proxy class in the Silverlight client app.

 
[EnableClientAccess()]
public class DemoDataService : DomainService
{
  [ServiceOperation]
  public string GetApplicationName()
  {
    return "Demo Ag Ria";
  }

  [ServiceOperation]
  public string GetApplicationAddress()
  {
    return "http://www.demoagria.com";
  }
}

To use the DemoDataService on the client, let's try the following code in the Home.xaml.cs file. Note the two additional using statements and take special note that all calls to the server are asynchronous:

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.IO;
using DemoAgRia.Web;
using System.Windows.Ria.Data;

namespace DemoAgRia
{
  public partial class Home : Page
  {
    public Home()
    {
      InitializeComponent();
    }

    // Executes when the user navigates to this page.
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
      DemoDataContext ddc = new DemoDataContext();
      InvokeOperation<string> invAddress = ddc.GetApplicationAddress();
      invAddress.Completed += new EventHandler(invAddress_Completed);
      
      InvokeOperation<string> invAppName = ddc.GetApplicationName();
      invAppName.Completed += new EventHandler(invAppName_Completed);
    }

    void invAppName_Completed(object sender, EventArgs e)
    {
      InvokeOperation<string> op = sender as InvokeOperation<string>;
      string appName = op.Value;
      this.ContentText.Text += string.Format("{0}app name: {1}", Environment.NewLine, appName);
    }

    void invAddress_Completed(object sender, EventArgs e)
    {
      InvokeOperation<string> op = sender as InvokeOperation<string>;
      string address = op.Value;
      this.ContentText.Text += string.Format("{0}address: {1}", Environment.NewLine, address);
    }

  }
}

If you F5 and run a debug test, you'll note that the text in the Home page gets modified as expected.

s5

Now let's add a RequiresAuthentication to the GetApplicationName method:

[ServiceOperation, RequiresAuthentication]
public string GetApplicationName()
{
  return "Demo Ag Ria";
}

Run the app again and you will notice that the GetApplicationName's InvokeOperation<string> object's Value property is null. Now login and click the About page link and then go back to the Home page link. Note that the text has maintained it's state. We're not clearing it, but this time we've added text which includes the app name.

s6

Now try modifying the GetApplicationAddress method like this:

[ServiceOperation, RequiresRoles("Supervisor")]
public string GetApplicationAddress()
{
  return "http://www.demoagria.com";
}

Since the stubbed role provider gives your logged in user the Admin and Analyst role, you can run this and see that you are getting a null value for the operation. Now change the role to "Admin" and try the same thing. This time when you login and come back to the Home page you'll see what we'd expect.

Getting this far was almost enough fun, but then I wondered how I would prevent a user from navigating to a specific Silverlight page if they were not authenticated. There are probably better ways, but here's the solution I arrived at after a little fiddling.

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

namespace DemoAgRia
{
  public class PageSecurity
  {
    private Page page;
    private string url;

    public PageSecurity(Page page)
    {
      this.page = page;
    }

    public void Authenticate()
    {
      Authenticate(null);
    }

    public void Authenticate(string url)
    {
      this.url = url;
      if (!RiaContext.Current.User.IsAuthenticated)
      {
        ErrorWindow ew = new ErrorWindow("You must be logged in to view this page.", 
          "Using this page is not allowed unless you are logged in.");
        ew.Title = "Authentication Required";
        ew.IntroductoryText.Text = "Not Authenticated";
        ew.LabelText.Text = "Message";
        ew.Closed += new EventHandler(ew_Closed);
        ew.Show();
      }
    }

    void ew_Closed(object sender, EventArgs e)
    {
      if (null == url)
        this.page.NavigationService.GoBack();
      else
      {
        if (!url.StartsWith("/")) url = "/" + url;
        try
        {
          this.page.NavigationService.Navigate(new Uri(url, UriKind.Relative));
        }
        catch
        {
          this.page.NavigationService.GoBack(); 
        }
      }
    }
  }
}

To test this code, I've added the following code to the About.xaml.cs code to see how it plays.

protected override void OnNavigatedTo(NavigationEventArgs e)
{
  PageSecurity ps = new PageSecurity(this);
  ps.Authenticate("Home");
}

Now all you have to do is download the code and you've got a headstart on Silverlight and .NET RIA Services security. Let me know if you find any exciting improvements or alternatives.