I love the [Authorize()] attribute in ASP.NET MVC for 2 main reasons:

  1. It’s easy to use.
  2. It “feels” lightweight.

I wish Silverlight/Prism had a similar security mechanism – but it doesn’t (at least not that I’ve found). Being new to the Silverlight scene I figured I’d take a stab at creating a reusable security mechanism that could be used in a stock Silverlight or Silverlight/Prism application.

The only requirements are that it must:

  1. Be easy to use.
  2. Feel lightweight.

Having said that, I wanted to post a code snippet of a Silverlight security solution that I feel captures the 2 requirements mentioned above.

<UserControl x:Class="Sandbox.Web.Shell.Shell"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:clr="clr-namespace:System;assembly=mscorlib"
    xmlns:local="clr-namespace:Sandbox.Web.Modules.Security.Converters;assembly=Sandbox.Web.Modules.Security">
    <UserControl.Resources>
        <local:AuthorizedEnabledConverter x:Key="ButtonEnabled" />
        <local:AuthorizedVisibleConverter x:Key="TextBlockVisible" />
        <clr:String x:Key="Authorization">Users=John,Jane;Roles=Administrator</clr:String>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Button Grid.Column="0" Grid.Row="0" Content="Click Me If You Can" IsEnabled="{Binding Source={StaticResource Authorization}, Converter={StaticResource ButtonEnabled}}" Margin="5" />
        <TextBlock Grid.Column="1" Grid.Row="0" Text="Hello World" Visibility="{Binding Source={StaticResource Authorization}, Converter={StaticResource TextBlockVisible}}" Margin="5" />
    </Grid>
</UserControl>

The important pieces of the XAML code above are the AuthorizedEnabledConverter and AuthorizedVisibleConverter converters declared in the UserControl.Resources section and how I used them in the Binding of the IsEnabled and Visibility properties of the Button and TextBlock. For the purposes of this post, I simply declared a static string resource with hardcoded users and roles, but this could just as easily be passed in as a property of a ViewModel or handled in a Presenter or Controller. The missing part of the puzzle (and the part I’m currently working on) is how I resolve the current user’s Username and roles within the converters.

So what does everyone think? Is this a viable security mechanism for Silverlight? Does it stay true to the requirements of being easy to use and lightweight?