Often a very simple MembershipProvider is required just to develop some features requiring user authentication and, perhaps, authorization.

Using MembershipProviderAdapter it is really very simple and straightforward. Follow the steps below to implement a MVC3 web application with a MembershipProviderAdapter.

1. Create a MVC3 project using Visual Studio MVC3 Internet Application template. This will add all the files necessary to add Forms authentications to the project.

2. Add a NuGet reference to the package named MembershipAdapter. It will add and reference the  MembershipAdapter. web.config will be changed to reflect the new providers:

  1:     <membership defaultProvider="MembershipProviderAdapter">
  2:       <providers>
  3:         <clear />
  4:         <!-- NOTE: Change userRepositoryType to whatever the implementation of IUserRepository is -->
  5:         <add name="AspNetSqlMembershipProvider" 
  6:               type="System.Web.Security.SqlMembershipProvider" 
  7:               connectionStringName="ApplicationServices" 
  8:               enablePasswordRetrieval="false" 
  9:               enablePasswordReset="true" 
 10:               requiresQuestionAndAnswer="false" 
 11:               requiresUniqueEmail="false" 
 12:               maxInvalidPasswordAttempts="5" 
 13:               minRequiredPasswordLength="6" 
 14:               minRequiredNonalphanumericCharacters="0" 
 15:               passwordAttemptWindow="10" 
 16:               applicationName="/" />
 17:         <add name="MembershipProviderAdapter" 
 18:               type="MembershipAdapter.MembershipProviderAdapter, MembershipAdapter" 
 19:               userRepositoryType="MvcApplication1.Samples.SampleUserRepository, MvcApplication1" 
 20:               enablePasswordRetrieval="false" 
 21:               enablePasswordReset="true" 
 22:               requiresQuestionAndAnswer="false" 
 23:               requiresUniqueEmail="false" 
 24:               maxInvalidPasswordAttempts="5" 
 25:               minRequiredPasswordLength="6" 
 26:               minRequiredNonalphanumericCharacters="0" 
 27:               passwordAttemptWindow="10" 
 28:               applicationName="MvcApplication1" />
 29:       </providers>
 30:     </membership>

The new MembershipProviderAdapter will be added and will be made the default one. userRepositoryType (line 19) is the type of the user repository that is injected in provider’s constructor. This where you can implement whatever logic is needed to support membership (and not only) users and their properties.

It is important to note that the user repository constructor expects a single parameter of type  MembershipProviderSettings. These are the settings that are listed on lines 20 thru 28.

3. Change ValidateUser method so that it returns true instead of throwing an exception

  1:         public bool ValidateUser(string username, string password)
  2:         {
  3:             return true;// throw new NotImplementedException();
  4:         }

Now every username and password combination would be accepted as valid one. (Of course, in a real scenario you wouldn’t allow that.)

4. Run the application and test the LogOn link. Whatever name you enter in User Name box is displayed in the welcome message. The user is authenticated and when you test IsAuthenticated property of the HttpRequest it is set to true.
Let us elaborate the example a bit. Say, except authenticated you need the user to be authorized. In addition, if username is admin you want him to be an administrator (i.e. to be in role Administrators).
5. Change shared partial view _LogOnPartial.cshtml

  1: @functions {
  2:     private bool IsAdministrator(string name)
  3:     {
  4:         return Roles.IsUserInRole("administrators");
  5:     }
  6: }
  7: @if (Request.IsAuthenticated)
  8: {
  9:     if (this.IsAdministrator(User.Identity.Name))
 10:         {<text>***</text>
 11:     }
 12:     <text>Welcome <strong>@User.Identity.Name</strong>! [ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
 13: }
 14: else
 15: {
 16:     @:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
 17: }
This will display three asterisks in front of the welcome message if user is administrator.
6. In order to check belonging to a role we need to modify GetRolesForUser method, part of the SampleRoleRepository class:
  1:         public string[] GetRolesForUser(string username)
  2:         {
  3:             if (username.Equals("Admin", StringComparison.OrdinalIgnoreCase))
  4:             {
  5:                 return new[] {"Administrators"};
  6:             }
  8:             return new[] { "Users" };
  9:         }

Last edited Dec 7, 2012 at 11:33 AM by ac2008, version 2


No comments yet.