Sunday, February 20, 2011

Membership, Profile and RoleManager on ASP.NET MVC II

We have coded more than once applications that need to handler user authentication and autorization in a certain way.

Perhaps we have done this using MembershipProvider in WebForm technology. However, Microsoft launched MVC Framework

that immediately became a big choice for Web developer who look for a fast and organized way to create Web Applications. Now,

we wonder how to implement MembershipProvider in MVC.



In the following tutorial will guide you to create a MembershipProvider using your AspNetSqlRoleProvider.

In other words, you will use your own database to store the user authentication information. Furthemore,

you will be able to manage the autorization based on role in the application, allowing user to access

specific views.





Let’s start.



  Step 1: Open the Web.Config file and look for the connectionStrings tag, you will find  the ApplicationServices connection string,

  if you don't, make sure your project is connected to a database server.

  Also, make sure on the connection string you have specified the correct database. As the example below you see that it is connected to TestDb.


<add name="ApplicationServices"

connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TestDb;Integrated Security=True"

providerName="System.Data.SqlClient" />





Step 2: Check on the web.config file if there is already a tag for authentication, membership,profile and roleManager.

As you can see on the example below the membership provider used on the application is AspNetSqlMembershipProvider

and it is linked this connection string  "ApplicationServices". You can customize its name




  <authentication mode="Forms">

  <forms loginUrl="~/Account/LogOn" timeout="2880" />

  </authentication>

  <membership>

  <providers>

  <clear/>

  <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"

    enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"

    maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"

    applicationName="/" />

  </providers>

  </membership>

  <profile>

  <providers>

  <clear/>

  <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />

  </providers>

  </profile>

  <roleManager enabled="false">

  <providers>

  <clear/>

  <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />

  <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />

  </providers>

  </roleManager>




 Until here you should not have done anything, unless you needed to change the connection string.




Step 3: Here is when the party starts. Run this executable [drive:]\%windir%\Microsoft.Net\Framework\v2.0.50727\aspnet_regsql.exe.

This will create tables, views and stored procedure on the database that you specify.










   



Step 4: when you execute the app I mentioned above, it'll pop up this window



image
   
   


Step 5: Since we want to create the sql server application, select the first option  "Configure Sql Server for application services" and Hit next



       



Step 7: Now we need to set the server name and the target database, be careful with choosing the target database,

 you might not want to create the bunch of objects in a wrong location, that may bring problem further.



   




Step 8: Click on Next









Step 9: If everything went okay, you will see the success message




   




Step 10: In order to check  what the app did on the database, open an instance of Microsoft SQL Server Management Studio,

you will see a set of tables, views and stored procedures were created.




   


Step 11: Now, returning to Asp.net mvc application, on Project menu select the last option "Asp.NET Configuration".

The Web Site Administration Tool lets you view and manage the Web site configuration through a simple Web interface.

Here is a good   documentation
what this tool does for us



image

       
   


Step 12: On the interface, we go directly the Security tab








Step 13: Create an user, you need to set up a password with minumn length of 6, otherwise you won't pass its validation.








Step 14: Now is time to enable the Role Manager, click on Security tab to go to the main screen. Click on Enable Roles




   



Step 15: Hit Create or Manage roles



   




Step 15: Add role






   





Step 16: Now, here we should manage the role, in other words, assign role to the user










Step 17: look for the user that you want to set role. In our example, we will set the role for the user "test"









Step 18: Check  User is in Role and we are done.



   




Until this point, we should enable the  the membership provider as well as role manager for our application.



Step 19: Going back to Visual Studio, a window should pop up, let's say Yes to All.

This is because we were changing the web.config file via interface.






Step 20: It's time to test it. Create a new controller. I called it "TestRoleController"






Step 21: Here is the important part, on the top of controller tag, we add the following [Authorize(Roles="admin")],

admin is the role that we defined previously.






Step 22: Now, you need to add the View. Create a folder under View folder, then add a new view called Index.aspx






Step 23: On Index.aspx add some text






Step 24: F5 to run the project







Step 25: You'll get into the home page





Step 26: Now when you try to get into a restricted page, you'll be redirected to the login page











 Step 27: If we provide the correct information, we should be able to get to the TestRole index page,

we will use the same user authentication we created on Step 13.





 Step 28: Eureka...






 
  I hope this tutorial could help you to have a better idea how to implement Membership provider and Role manager in asp.net mvc





  

2 comments:

  1. Is the view model using the same concept? Thanks, Felix

    ReplyDelete
  2. umm WTF DOES RoleManager do?? please at least explain that.

    ReplyDelete