.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month

Home >> Articles >> Silverlight >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Authentication using custom Table In SL4 Using RIA Service

Posted By:Manas Patnaik       Posted Date: March 21, 2011    Points: 200    Category: Silverlight    URL: http://www.dotnetspark.com  

Implementing Forms Authentication using custom table in RIA Service and Entity Framework

In my previous article we had discussed about Data Binding ,Validation,Exception Handling ,Handling Multiple table and many more.But the first step in a business application deals with Authentication.Surely nobody wants data to be meshed up by an anonymous user so in this article we are going to implement Authentication to SOI (Satate of India) application.This post is restricted to FormsAuthentication model only.Also i am going to skip Authorization and due for next article.

Well authentication in Silverlight 4 using RIA service in business application can be implemented by 2 ways

  • Using Default authentication provided by Silverlight Business Template (Using ASP.Net Role and Membership)
  • Using Custom Authentication (Using your own database and  model )

You can find number of post/articles available in blogs that's deals with default authentication with Asp.Net membership provider .If you want to find know more about  this MSDN article worth a look .

SO lets start with Authentication using your own custom table for application.


This article going to demonstrate the steps involved for integrating  authentication to States of India (SOI App) using a custom table which will store basic information such as UserName,Password and Email.Before proceeding with SOI app lets have a look into the app with my previous articles.

Custom Authentication  using RIA Services

So here the application aim to have following functionality

  1. The User have access to the Home page , where they can view the State and its information
  2. But Adding a new state or Editing state requires user to be authenticated

Steps Involved For Implementing Authentication

Before going into detail of each steps the image bellow shows a overall picture/steps.Follow the Arrow mark for sequence , as there is a human tendency of reading Left to Right Smile.

Custom Authentication  using RIA Services

Adding a new Table to Database and Updating the Data model

The first step is to add a table to application database , here i have added a new table called UserDetail with following fields.

Custom Authentication  using RIA Services

Then go to your Model at server side project and update the Model.In case you need the detail of setting up a Entity Data Model then refer to my earlier post Here.

Custom Authentication  using RIA Services

Select the newly added UserDetail table and proceed.Along with the newly added entity to data model it will be as bellow.If you notice than you can mark that the UserName column in the  table is mapped as Name to UserDetail entity , we will discuss about it later in this post.

Custom Authentication  using RIA Services

The Basic Server Side Setup for Custom Authentication

Changes to WebConfig File

As we opted for Forms Authentication, the very first change we need is to add the authentication in webconfig file.So add following section to the webconfig file at server side project.

  1. <authentication mode="Forms">
  2. authentication>
The Concept

Before i proceed with rest of the article lets have a look into some concept and how it will work.When you use a business template in Silverlight ,visual Studio adds Authentication service derived from AuthenticationBase and User Derived form UserBase.The user information and roles are stored with default ASP.Net membership provider table ASPNETDB.

But we are going to use UserDetail table instead of default ASPNETDB and our own Domainservice to handle authentication.Here comes the IAuthentication and Iuser interfaces.

Custom Authentication  using RIA Services

So our Custom DomainService is going to be implement IAuthentication , where T is the type of UserDetail,  in turns the interface will make available the UserDetail to both client and server side.

As the UserDetail entity is going to be propagated to client side using IAuthentication it requires to implement IUser interface.The update of Entity Data Model add UserDetail entity to model and generates  following piece of code along side State and City entity.

Custom Authentication  using RIA Services

Our Database Table does not holds  Name property as its required from IUser interface point of view  ,so we need to map UserName to Name in UserDetail entity.You can avoid this step If your table has a Name column .For the time being here i am going to skip Role as implemented by IUser.

Custom Authentication  using RIA Services

Then lets add a class named UserDetail to implement IUSer interface,Custom Authentication  using RIA Services

  1. public partial class UserDetail : IUser
  2. {
  3. #region IUser Members
  4. [DataMember]
  5. public IEnumerable<string> Roles
  6. {
  7. get
  8. {
  9. return null;
  10. }
  11. set
  12. {
  13. throw new NotImplementedException();
  14. }
  15. }
  16. #endregion
  17. }
  18. }

So partial classes for UserDetail at EntityModel and above UserDetail sets the valid User which is going to be use  in the Custom Authentication domain service ,which we are going to add in  next Step.

Adding a DomainService for Authentication

Lets add a new DomainService named SOIAuthDomainService , with out selecting any entity .In the Domain service implement IAuthentication interface

Custom Authentication  using RIA Services

Here in SOIAuthDomainService along with the default methods we will add some more method for Validation and insertion of a user.And also implement logic for Login,Logout .The DefaultUser is  the user we are going to return in case the login failed.So overall the class structure will be as bellow

Custom Authentication  using RIA Services

The Login Logic in the domain service as follows

  1. public UserDetail Login(string userName, string password, bool isPersistent, string customData)
  2. {
  3. if (this.ValidateUser(userName, password))
  4. {
  5. FormsAuthentication.SetAuthCookie(userName, isPersistent);
  6. return this.GetUser(userName);
  7. }
  8. return null;
  9. }

while the ValidateUser logic follows as bellow

  1. private bool ValidateUser(string username, string password)
  2. {
  3. return this.ObjectContext.UserDetails.Any(u => u.Name == username && u.Password == password);
  4. }

As we are allowing User Registration so here let add InsertUser Method ,later in this post we will check with implementation

  1. public void InsertUser(UserDetail user)
  2. {
  3. if ((user.EntityState != EntityState.Detached))
  4. {
  5. this.ObjectContext.ObjectStateManager.ChangeObjectState(user, EntityState.Added);
  6. }
  7. else
  8. {
  9. this.ObjectContext.UserDetails.AddObject(user);
  10. }
  11. }

Client Side Setup

The next step is to add the Registration Service to the ApplicationLifeTime so that it can be accessed using WebContext.Current.When you built a RIA project it automatically Creates a WebContext Class at client side which holds information Authentication and Current User.Here check with the client side generated code

Custom Authentication  using RIA Services

So in the App.Xaml.cs add followings

  1. // Create a WebContext and add it to the ApplicationLifetimeObjects
  2. // collection.  This will then be available as WebContext.Current.
  3. WebContext webContext = new WebContext();
  4. webContext.Authentication =
  5. new System.ServiceModel.DomainServices.Client.ApplicationServices.FormsAuthentication();
  6. //webContext.Authentication = new WindowsAuthentication();
  7. this.ApplicationLifetimeObjects.Add(webContext);

Implementing Authentication Logic at UI

Lets add Login And UserRegistration Screens to client side Silverlight project.

Custom Authentication  using RIA Services

As my intention is to give a clear picture on authentication , i have-not added any validation logic what so ever.For more information on adding validation logic refer my earlier post here.

So coming to this post ,lets check with the Login screen.

Login  Screen

With the the user input details and on Ok Button click the user credential validated against database using the service.The commented code is self explanatory for each line of code and its intentions.

  1. private void OKButton_Click(object sender, RoutedEventArgs e)
  2. {
  3. biCreateUser.IsBusy = true;
  4. //Attach The Authentication_LoggedIn For Displaying the User Status
  5. //On MainPage once the user Logged In
  6. WebContext.Current.Authentication.LoggedIn +=
  7. new EventHandler<AuthenticationEventArgs>(Authentication_LoggedIn);
  8. //Call WebContext.Current.Login
  9. LoginOperation lop=  WebContext.Current.Authentication.Login
  10. ((new LoginParameters(txtUserName.Text, txtPassword.Text, true, null)));
  11. //Callback to Login Operation
  12. lop.Completed += (Authsender, args) =>
  13. {
  14. if (!lop.HasError)
  15. {
  16. if (lop.LoginSuccess)
  17. {
  18. this.DialogResult = true;
  19. }
  20. else
  21. {
  22. lblAuthStatus.Content = "Login Failed";
  23. }
  24. }
  25. else
  26. {
  27. MessageBox.Show(lop.Error.Message);
  28. lop.MarkErrorAsHandled();
  29. }
  30. biCreateUser.IsBusy = false;
  31. };
  32. }

Once the Login operation completed successfully  and the on login screen close ,we will  display the UserName on main page header.

Custom Authentication  using RIA Services

So i am going to add a method called UpdateStatus in the Mainpage.Xaml.cs and will call it on the login window close.

  1. private void ChildWindow_Closed(object sender, EventArgs e)
  2. {
  3. MainPage mpage = (MainPage)App.Current.RootVisual;
  4. mpage.UpdateStatus();
  5. }

Using Webcontext.Current we can  check weather the client using the app is authenticated or not.

  1. WebContext.Current.Authentication.User.Identity.IsAuthenticated

So the Update Status code follows as bellow

  1. public void UpdateStatus()
  2. {
  3. //Check if Client is Authenticated
  4. if (WebContext.Current.Authentication.User.Identity.IsAuthenticated)
  5. {
  6. lblUser.Visibility = System.Windows.Visibility.Visible;
  7. //Assign The Username to screen
  8. lblUser.Content = WebContext.Current.Authentication.User.Identity.Name;
  9. hbLogin.Content = "Logout";
  10. }
  11. else
  12. {
  13. lblUser.Visibility = System.Windows.Visibility.Collapsed;
  14. hbLogin.Content = "Login";
  15. }
  16. }
User Registration

As shown in picture the user have a option to Register in the Login screen and on demand the UserRegistration screen popup for adding a new user.The InsertUserDetail method in the SOIAuthentication DomainService class will be called on addition of a new user.

  1. private void OKButton_Click(object sender, RoutedEventArgs e)
  2. {
  3. //New Domain Context Objext
  4. SOIAuthDomainContext domContext = new SOIAuthDomainContext();
  5. //New UserDetail Object from User Input
  6. UserDetail uDetail=new UserDetail();
  7. uDetail.Name=txtUserName.Text;
  8. uDetail.Password=txtPassword.Text;
  9. uDetail.Email=txtEmail.Text;
  10. biWait.IsBusy = true;
  11. //Add to DomainContext UserDetail collection
  12. domContext.UserDetails.Add(uDetail);
  13. //Call InsertUserDetail with SubmitChanges
  14. SubmitOperation authSO= domContext.SubmitChanges();
  15. authSO.Completed += (authsender, args) =>
  16. {
  17. if (!authSO.HasError)
  18. {
  19. MessageBox.Show("User Created");
  20. this.DialogResult = true;
  21. }
  22. else
  23. {
  24. MessageBox.Show(authSO.Error.Message);
  25. authSO.MarkErrorAsHandled();
  26. }
  27. biWait.IsBusy = false ;
  28. };
  29. }

The Final Punch

The above step lays the foundation for authentication and the Webcontext.Current can be used through out the project for additional constraint for each functionality.For e.g in SOI app , the AddNewState and EditState is now onwards open for authenticated User only.

Custom Authentication  using RIA Services


Microsoft suggest to follow ASP membership provide model for Authentication as it provide more reusability and more security.But authentication using custom table some times un avoidable .I hope this article will help you in many ways either using multiple Domain Services ,knowing application classes and of course authentication.Keep posting suggestions.

Source Code and Live Link

Live Link - SOI App

Source Code - StatesOfIndia_Authentication.zip

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend