Silverlight pages that Require login, part 1

This page is part 1 in a series of pages about “Silverlight pages that require login”. The parts are part 1, part 2 and part 3.

I’m evaluating using Silverlight and RIA services to create a web based application. Right now I’d like to set something like this up;

  1. Some links – secured links – cannot be clicked unless you’re logged in – part 1
  2. If the user logs in, the secured links should automatically be enabled – part 1
  3. If the user logs out, the secured links should automatically be disabled – part 1
  4. If the user logs out while accessing a page that requires authentication, the user should be booted off the page – part 2
  5. If anyone directly accesses a page that requires authentication, the user shouldn’t see any information on the page – all information on the page is to be considered sensitive. part 2
  6. If the user is logged off while on the on the page, then the user should be booted off the page – part 2
  7. If the user isn’t logged in, the user should be asked to log in and if that fails, he should be booted to the main page. This is similar to 5 but 5 is about prohibiting access, this is about allowing login then access and the prohibition is a fallback – part 3

This blog post will outline my struggles as I try to make this happen.

First, I added a link that eventually will required authentication/that the user is logged in. Initially, it’s enabled even when the user isn’t logged in;

Then I added a property that the link can bind to, to determine if the user is authenticated or not;

        public bool IsAuthenticated
        {
            get
            {
                return WebContext.Current.User.IsAuthenticated;
            }
        }

I also have to set the datacontext to “this” to allow the xaml to bind to the backing properties;

        public MainPage()
        {
            InitializeComponent();
            this.DataContext = this;
            this.loginContainer.Child = new LoginStatus();
        }

Next I bound the IsEnabled property of the link to my new property;

 <HyperlinkButton
 x:Name="Link3"
 Style="{StaticResource LinkStyle}"
 NavigateUri="/DemoPage"
 TargetName="ContentFrame"
 Content="demo (requires login)"
 IsEnabled="{Binding Path=IsAuthenticated}"/>

Now the link is disabled when I start the application;

But it’s not enabled when I login! That’s because I need to add an event that refreshes the property whenever the user logs in or logs out. That requires a digression where we make the main page implement INotifyPropertyChanged so that I could create a bindable property that handles change notification;

    public partial class MainPage : UserControl,  INotifyPropertyChanged
    {
         public event PropertyChangedEventHandler PropertyChanged;

Then I added this code to allow me to use “type safe” methods with INotifyPropertyChanged;

        public event PropertyChangedEventHandler PropertyChanged;

 protected static string GetPropertyName<T>(Expression<Func<T>> action)
 {
 var expression = (MemberExpression)action.Body;
 return expression.Member.Name;
 }

 protected virtual void SendPropertyChanged<T>(Expression<Func<T>> action)
 {
 string propertyName = GetPropertyName(action);
 SendPropertyChanged(propertyName);
 }

 private void SendPropertyChanged(string propertyName)
 {
 if (PropertyChanged != null)
 {
 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
 }
 }

Back on track, we’re now ready to send notifications whenever a the user logins in our out. A bit of research shows that WebContext.Current.Authentication is responsible for this. So hooking that up as shown below makes the link enable/disable appropriately(notice the wonderful use of lambda instead of delegates, good or bad? You decide);

        public MainPage()
        {
WebContext.Current.Authentication.LoggedIn +=
 (sender, e) => SendPropertyChanged(() => IsAuthenticated);
 WebContext.Current.Authentication.LoggedOut +=
 (sender, e) => SendPropertyChanged(() => IsAuthenticated);

            InitializeComponent();
            this.DataContext = this;
            this.loginContainer.Child = new LoginStatus();
        }

Here’s a shot when the user’s logged out and the link is disabled;

Next I’ll make the page refuse users that are logged out – or at least force them to log in. Check out part 2 that describes how to do that.

About mfagerlund
Writes code in my sleep - and sometimes it even compiles!

7 Responses to Silverlight pages that Require login, part 1

  1. Pingback: Silverlight pages that require login, part 2 « Mattias Fagerlund's Coding Blog

  2. Pingback: Silverlight pages that require login, part 3 « Mattias Fagerlund's Coding Blog

  3. Pingback: IsAuthenticated in Silverlight, Revisited « Mattias Fagerlund's Coding Blog

  4. David says:

    Nice quick write-up of how to do the basic notifying of login / logout events, thanks!

  5. Robert says:

    I’ve implemented steps 2,3 & 4 in my Silverlight 4 sp1 Business Application Template project, but in step 1 in the MainPage.xaml.cs I can’t find the ‘loginContainer’

    this.loginContainer.Child = new LoginStatus();

    when I type this. intelisense shows nothing for ‘loginContainer’

    Did something change in Sivlerlight 4 sp1 that breaks this? Am I missing something simple?

    Thanks so much, your tutorial has already been a huge help.

    Robert

    • Robert says:

      Just answered my own question looking at another tutorial.

      For other that might need the help

      in MainPage.xaml at the bottom you’ll find (I’ve names the boder (x:Name=”loginContainer”)

      • sonu says:

        hey hi.
        i m new to silverlight…its great tutorial thanks in advance..help me
        i did the same thing as said..i changed at bottom but the problem is i can see the changes in mainpage.xaml file but if i debug changes are not reflected to the html page in browser.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: