Silverlight, Minimal Authentication Implementation

I previously blogged about Silverlight and ASP.NET Authentication Woes, but my colleague Robin Dunlop pointed out that there is a simpler way, and sure enough, there is! I only needed to override/implement three methods, two in AuthenticationService (ValidateUser and GetAuthenticatedUser) and one method in UserRegistrationService (AddUser).

Below you’ll find a truly minimal implementation;

  • It will not retain user accounts after a system restart
  • It will expect passwords to match the username (very bad security…)
  • It will come with a user called “Bobby” (password Bobby)

AuthenticationService

using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web.Ria;
using System.Web.Ria.ApplicationServices;

namespace BusinessApplication1.Web
{
    [EnableClientAccess]
    public class AuthenticationService : AuthenticationBase<User>
    {
        private static List<User> _users = new List<User> { new User { Name = "Bobby" } };

        public static List<User> Users { get { return _users; } }

        protected override bool ValidateUser(string userName, string password)
        {
            if (_users.Exists(user => user.Name.Equals(userName)) == false)
            {
                return false;
            }

            return userName == password;
        }

        protected override User GetAuthenticatedUser(IPrincipal pricipal)
        {
            return _users.Where(user => user.Name.Equals(pricipal.Identity.Name)).SingleOrDefault();
        }
    }
}

UserRegistrationService

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
        public void AddUser(RegistrationData user)
        {
            User newUser =
                new User
                    {
                        FriendlyName = user.FriendlyName,
                        Name = user.UserName                        
                    };

            AuthenticationService.Users.Add(newUser);
        }

A real world implementation…

A real world implementation would require you to actually store the user in some kind of persistent storage, but I’m leaving that as an exercise for the user.

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

One Response to Silverlight, Minimal Authentication Implementation

  1. Pingback: ASP.NET (and Silverlight) authentication woes « Mattias Fagerlund's Coding Blog

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: