Security is a key component of applications and something that developers often struggle with to get right. How do you authenticate a user? How do you integrate roles and use them to show or hide different parts of a screen? These and other questions commonly come up as I talk with developers working on ASP.NET and Silverlight applications.

While I was presenting a workshop on Silverlight at the DevConnections conference in Orlando last March, an audience member asked me a question about how I handle security roles in Silverlight applications. Since I had just implemented a security mechanism for a customer, I gave a brief response but didn't have a sample application available to share to point people in the right direction. After the workshop was over, I put together a sample application to demonstrate one potential approach for accessing usernames and roles. I'll walk through the sample application in this article and highlight the key components.

The goal of the article isn't to dictate how to authenticate users, since every application has unique requirements. However, I will discuss general techniques for accessing usernames and working with roles to block access to views and show or hide controls.

Working with Security

Silverlight applications can take advantage of Windows and Forms authentication techniques and can integrate user roles into the mix as well. However, unless you use Windows Communication Foundation (WCF) RIA Services on the back end, you'll need to write the plumbing code to authenticate a user if you need to do so directly within the application. WCF RIA Services projects provide login and registration screens out of the box that leverage Forms authentication by default. You can view a walk-through of the WCF RIA Services authentication process.

WCF RIA Services also provides a means for accessing an authenticated user's username and roles by using a WebContext object. This isn't possible out of the box in a standard Silverlight application unless you write custom code to handle it. If WCF RIA Services is appropriate for your project, then it's a great way to go for handling data exchange and security tasks. If you won't be using WCF RIA Services, then this article will provide insight into other techniques that can be used.

Most of the Silverlight line-of-business (LOB) applications I've worked on authenticate the user at the page level using Windows authentication. If the user can't authenticate into the page, then the Silverlight application is never displayed. With out-of-browser applications, the Windows user account can be passed through and accessed as calls to a service are made. The sample application available with this article assumes that authentication occurs at the page level as opposed to within the Silverlight application itself.

Accessing the Username

To access an authenticated user's username within a Silverlight application, you can either pass the username into the object tag's initialization parameter (called "initParams") or call a service that returns the username. Following is an example of passing in the username using the initParams option within an ASP.NET page that is hosting the object tag.

  1. <param name="initParams" value="UserName=<%=User.Identity.Name%>" />

Within App.xaml.cs you can access the initParams parameters and store them. The code in Figure 1 shows how to do this and add initParams values into the application resources so that they can be accessed throughout the application.

  1. private void Application_Startup(object sender, StartupEventArgs e)
  2. {
  3.     ProcessInitParams(e.InitParams);
  4.     this.RootVisual = new MainPage();
  5. }
  7. private void ProcessInitParams(IDictionary<string, string> initParams)
  8. {
  9.     if (initParams != null)
  10.     {
  11.         foreach (var item in initParams)
  12.         {
  13.             this.Resources.Add(item.Key, item.Value);
  14.         }
  15.     }
  16. }

My own preference is not to embed the username into the object tag unless it's merely going to be displayed in the application. If you'll be doing lookups against different databases or other resources based on the username, it's better to let a service resolve the username dynamically so that it can't be spoofed. Otherwise, a user who authenticated into the application could potentially change the username defined in initParams and bypass security.

To access the username using a service, you can create a WCF security service as shown in Figure 2 and add an operation that is responsible for returning the username. The easiest way to create the service is to add a Silverlight-enabled WCF service into the web project.

  1. [ServiceContract(Namespace = "")]
  2. [SilverlightFaultBehavior]
  3. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  4. public class SecurityService
  5. {
  6.     [OperationContract]
  7.     public string GetLoggedInUserName()
  8.     {
  9.         return new SecurityRepository().GetUserName(OperationContext.Current);
  10.     }
  12.     [OperationContract]
  13.     public List<Role> GetRoles()
  14.     {
  15.         return new SecurityRepository().GetRoles();
  16.     }
  18.     [OperationContract]
  19.     public UserSecurity GetUserSecurity()
  20.     {
  21.         return new SecurityRepository().GetUserSecurity(OperationContext.Current);
  22.     }
  23. }

The codein Figure 2 contains a GetLoggedInUserName() operation that makes a call into a SecurityRepository class's GetUserName() method to access the username. GetUserName() accesses the username through the OperationContext object's ServiceSecurityContext property, which provides access to the user's identity object. (Note that specific configuration changes must be made for this object to be useful—see the sample project's web.config file for more details.)

Figure 3 shows the code in the SecurityRepository class. The class simulates roles by adding them directly into the code but could easily be enhanced to retrieve roles from a database or another store.

  1. public class SecurityRepository
  2. {
  3.     //Simulate roles
  4.     List<Role> _Roles = new List<Role>();
  6.     public SecurityRepository()
  7.     {
  8.         _Roles.Add(new Role { Name = "Admin" });          
  9.         _Roles.Add(new Role { Name = "Editor" });
  10.         _Roles.Add(new Role { Name = "User" });
  11.     }
  13.     public string GetUserName(OperationContext opContext)
  14.     {
  15.         return GetOpContextUserName(opContext);
  16.     }
  18.     public List<Role> GetRoles()
  19.     {
  20.         return _Roles;
  21.     }
  23.     public UserSecurity GetUserSecurity(OperationContext opContext)
  24.     {
  25.         var userName = GetOpContextUserName(opContext);
  27.         if (userName != null)
  28.         {
  29.             return new UserSecurity { UserName = userName, Roles = _Roles };
  30.         }
  31.         return null;
  32.     }
  34.     private string GetOpContextUserName(OperationContext opContext)
  35.     {
  36.         return (opContext.ServiceSecurityContext != null &&
  37.                 opContext.ServiceSecurityContext.WindowsIdentity != null) ?
  38.                 opContext.ServiceSecurityContext.WindowsIdentity.Name : null;
  39.     }
  40. }

The GetUserSecurity() method provides a way for the Silverlight application to make a single call and get the username and roles for the authenticated user. This method is called by the Silverlight client and used to show and hide controls within the application. Let's take a look at how that process works.

Creating a SecurityManager for Silverlight

The WCF service shown in Figure 2 provides a way for a Silverlight application to retrieve a username and roles. How do you go about calling the service and storing the resulting information? For a recent customer application, I created a SecurityManager class that was responsible for storing username and role information and exposing properties such as IsAdmin and IsEditor to handle determining what role a user was in. It went through a service agent class that was responsible for calling the WCF service and returning the data to the SecurityManager. By going this route, you make a single class responsible for security, which avoids scattering security logic throughout an application. Figure 4 contains the code for the SecurityManager class available with the sample application.

The key part of the SecurityManager class is found in the constructor, where a call is made to another class named SecurityServiceAgent (a "service agent" that specializes in data retrieval) to retrieve the username and roles from the WCF security service shown earlier. Since the service call is asynchronous, an event is defined in SecurityManager named UserSecurityLoaded that is raised once the data is loaded in the Silverlight client.

In addition to getting and storing user data, the SecurityManager class also has methods such as UserIsInAnyRole() to check whether the user is a member of an array of roles, UserIsInRole() to check whether they're in a specific role, and CheckUserAccessToUri() to verify whether or not they have access to a specific view. Properties such as IsAdmin and IsEditor provide a simple way for consumers of the SecurityManager class to check whether a user is in a role specific to the application.

Using the SecurityManager Class

The SecurityManager class can be used directly in views or within ViewModel classes. When using the MVVM pattern, you can add a property into a ViewModel base class (a class that all ViewModel classes derive from), as shown next:

  1. public ISecurityManager SecurityManager { get; set; }

This property allows security functionality to be available across all ViewModel classes. The sample application contains two ViewModel classes—named MainPageViewModel and HomeViewModel—that use SecurityManager. MainPageViewModel uses the SecurityManager class to render the username in the MainPage.xaml view and hide any HyperlinkButton controls that a user shouldn't be able to see. Figure 5 shows the complete code for MainPageViewModel.

  1. public class MainPageViewModel : ViewModelBase
  2. {
  3.     private bool _IsAdmin;
  4.     private string _UserName;
  6.     public MainPageViewModel()
  7.     {
  8.         if (!IsDesignTime) SecurityManager.UserSecurityLoaded +=
  9.           SecurityManagerUserSecurityLoaded;
  10.     }
  12.     public bool IsAdmin
  13.     {
  14.         get
  15.         {
  16.             return _IsAdmin;
  17.         }
  18.         set
  19.         {
  20.             if (_IsAdmin != value)
  21.             {
  22.                 _IsAdmin = value;
  23.                 OnNotifyPropertyChanged("IsAdmin");
  24.             }
  25.         }
  26.     }
  29.     public string UserName
  30.     {
  31.         get
  32.         {
  33.             return _UserName;
  34.         }
  35.         set
  36.         {
  37.             if (_UserName != value)
  38.             {
  39.                 _UserName = value;
  40.                 OnNotifyPropertyChanged("UserName");
  41.             }
  42.         }
  43.     }
  46.     void SecurityManagerUserSecurityLoaded(object sender, EventArgs e)
  47.     {
  48.         IsAdmin = SecurityManager.IsAdmin;
  49.         UserName = SecurityManager.UserName;
  50.     }
  51. }

MainPageViewModel starts by attaching to the SecurityManager's UserSecurityLoaded event. Once the event fires, SecurityManagerUserSecurityLoaded is called and the IsAdmin and UserName properties are assigned to the ViewModel's properties. These properties are then bound to controls in the view using standard Silverlight data-binding techniques. The IsAdmin property is bound to HyperlinkButton controls and used to show or hide the controls based on whether or not the user is in the Admin role. A value converter is used in the view to handle converting the Boolean value to a Visibility enumeration value. The UserName property is bound to a TextBlock control that displays the username in the interface.

HomeViewModel uses the SecurityManager class to determine whether or not edit controls that allow customer information to be saved and edited should be present. If the user is in the Admin or Editor role, then the controls are shown. If not, the controls are hidden.

Securing Individual Views

Although accessing username and role functionality is important in order to customize the user interface based on the user's security rights, in many cases, you'll also need to secure individual views. For example, the MainPageViewModel defines an IsAdmin property (shown inFigure 5) that is used to show or hide a HyperlinkButton to prevent a user from going to a specific view. However, if the user knows the path to the view, they can type it directly into the browser's URL and load the view directly, bypassing the intended security. To prevent this, the CheckUserAccessToUri() method in the SecurityManager class (see Figure 4) can be used in conjunction with the Navigating event of the Frame within MainPage.xaml (the Frame control is included since the sample project uses the Silverlight navigation application project template).

Figure 6 shows the code that handles checking when a user has access to a specific view as the Frame in MainPage.xaml loads content. The code shown in MainPage_Loaded handles attaching to the Frame's Navigating event. When the event is raised, the code in the ContentFrame_Navigating event handler cancels the Navigating event if the user isn't determined to be a valid user. It also makes the call to the CheckUserAccessToUri() method to determine whether the user is allowed to get to the view that the content Frame is attempting to load. If the user doesn't gain access, a view named AccessDenied.xaml is loaded, which displays the appropriate Access Denied error message.

  1. void MainPage_Loaded(object sender, RoutedEventArgs e)
  2. {
  3.     ViewModel = (MainPageViewModel)this.Resources["ViewModel"];
  4.     ViewModel.SecurityManager.UserSecurityLoaded +=
  5.      SecurityManagerUserSecurityLoaded;
  7.     ContentFrame.Navigating += ContentFrame_Navigating;
  8. }
  10. void SecurityManagerUserSecurityLoaded(object sender, EventArgs e)
  11. {
  12.     //Cause frame to navigate to view user originally wanted to see
  13.     ViewModel.SecurityManager.UserSecurityLoaded -=
  14.        SecurityManagerUserSecurityLoaded;
  15.     ContentFrame.Navigate(ContentFrame.Source);
  16. }
  18. private void ContentFrame_Navigating(object sender, NavigatingCancelEventArgs e)
  19. {
  20.     //No username or roles found
  21.     if (!ViewModel.SecurityManager.IsValidUser)
  22.     {
  23.         e.Cancel = true;
  24.         return;
  25.     }
  27.     //Check if user has access to page that they're trying to navigate to
  28.     var hasAccess = ViewModel.SecurityManager.CheckUserAccessToUri(e.Uri);
  29.     if (!hasAccess)
  30.     {
  31.         ContentFrame.Content = new AccessDenied();
  32.         e.Cancel = true;
  33.     }
  34. }

Security Is Crucial

Security is an important part of LOB applications and something that definitely must be thought through and planned carefully. In this article you've seen different ways to access a username and associated roles in a Silverlight application. You've also seen how a SecurityManager class can be created to perform security checks that are used by ViewModel classes to show or hide controls.

To the person in the DevConnections workshop mentioned at the beginning of this article, thanks for asking the question, and I hope the sample application helps get you started in the right direction integrating security features into your Silverlight applications.