Click here to Skip to main content
Click here to Skip to main content

Custom Membership, Role Providers, Website administration tool, and Role based access to individual files

By , 12 Jul 2011
 

Sample Image

Introduction

I present here a sample custom membership provider and a custom role provider. This article explains how to easily implement your own custom providers using your own simple custom database.

In addition, I will provide a complete website administration tool which can edit website settings. It has a create/edit/manage users feature and a create/edit/manage roles feature.

Finally, I will introduce a different approach towards role based access control to individual files. The information about multiple ASPX files is stored in an "Activities" database. Through the website administration tool, we can assign role based access rights to individual ASPX files. (The code is just an example for the point which I want to make. I have tested the providers, but the Activities module has not been tested for production yet. I would appreciate feedback and expert advise as well for the same so that I will be able to improve it.)

If you want to override my approach with the default role based access to directories, try storing the location to the folders instead, with "/" included at the end. I have written two methods, "allowfolderaccess" and "denyfolderaccess", using the classic System.Web.Configuration approach.

Background

If you want form based authentication and role based authorization in your website, you can use the Membership API and the Role API of the .NET Framework. The fun in using these is that, if you do not want to create your own classes and database structure and still want a strong membership and role management feature in place, you can use the default providers which are inbuilt into the database. These default providers create a default database, ASPNETDB, and stores the information about the users and roles in this database.

A much bigger advantage with this feature is that, if you do not want to use the default classes and default database but want your own database structure, you can modify the entire behaviour of your web application according to your needs. The only thing you have to take care is that you will have to implement a defined set of interfaces in your class so that the API can use it. The Membership API and Roles API have a defined set of interfaces which you will have to implement. For example, the MembershipProvider interface for the Membership API, the RoleProvider interface for the Roles API, the ProfileProvider for the Profiles API etc.

Now, how do you do it? Just create a new class in the App_Code folder named MyMembershipprovider, or use any name which you like, and make it implement MembershipProvider like this:

public class MyMembershipProvider : MembershipProvider

Then, right click on the MembershipProvider and click on "Implement Abstract Class". Blank functions are created automatically, and the only thing you have to do is fill in the blanks.

The proper steps to use a custom membership provider are:

  1. Configure Forms Authentication in your web.config file as usual, and deny access to anonymous users. Like this:
    <authentication mode="Forms">
    <forms name="code-pro-ject" loginUrl="login.aspx" />
    </authentication>
    <authorization>
    <deny users="?"></deny>
    <allow roles="Administrator"></allow>
    </authorization>
  2. Set up the data store. For example, if you are using SQL Server, you have to create the necessary tables and Stored Procedures in a SQL Server database of your choice. I have created the following tables:

  3. In the web.config file, configure the database connection string and the Membership Provider you want to use, like this:
    <connectionStrings>
        <add name="UsersDb" 
          connectionString="Server=.\SQLExpress;Database=SampleDb;
             Integrated Security=True;AttachDbFilename=|DataDirectory|UsersDb.mdf;
             User Instance=True;" 
          providerName="System.Data.SqlClient"/>
    </connectionStrings>

    and......

    <membership defaultProvider="MyMembershipProvider" userIsOnlineTimeWindow="20">
    <providers>
    <clear/>
    <add name="MyMembershipProvider"
    type="MyMembershipProvider"
    connectionStringName="UsersDb"
    enablePasswordRetrieval="false"
    enablePasswordReset="true"
    requiresUniqueEmail="false"
    requiresQuestionAndAnswer="false"
    passwordStrengthRegularExpression=""
    minRequiredPasswordLength="1"
    minRequiredNonalphanumericCharacters="0"
    passwordFormat="Hashed"
    applicationName="/" />
    </providers>
    </membership>
    
    <roleManager enabled="true" defaultProvider="MyRoleProvider">
    <providers>
    <clear/>
    <add name="MyRoleProvider" connectionStringName="UsersDb"
      applicationName="/"
      type="MyRoleProvider" />
    </providers>
    </roleManager>
  4. Create users in your Membership store using the ASP.NET web configuration utility, or using a custom website administration page which you can make yourself.
  5. Create a login page that uses the prebuilt Login control, or create a login page that uses the Membership class for validating the entered credentials and authenticating the user.

Using the code

You can download the code provided with this article and directly copy the code to your machine to check the functionality. You can change the name of the database in the web.config file's connectionStrings settings.

I have tested the application to be working fine with my Activities thing included into it. If you do not want to use the activity thing and are only interested in a custom Membership Provider and a custom Role Provider, you can just store the location of the folders with "/" included in the end in the Activities database, and it should work fine.... I have included functions for this (but I have not properly checked them.. please bear with me until I test it further, as I am presently working on the Activities thing).**

I have not used any Stored Procedures in these providers, so you can easily include the fields which I am using into your tables and change the SQL statements accordingly. This means you can integrate it into your own website with lesser effort.

**Please note that the web.config files in the sub directories of this project do not have xmlns="..." attributes to their configuration elements. This is because I am not very good at namespaces. The first update which I will post will be able to handle this. However, if you only storing folder information, I think it will work fine because it does not uses my Datamanager class; instead, it uses System.Web.Configuration's classes to modify access rights.

Note

Please follow the corrections suggested by zemma for Admin/Roles/Default.aspx: Button1_Click, Admin/Roles/Default.aspx: Button2_Click, and Admin/Roles/Default.aspx: denyfolderacces in the messages posted to this article below.

Other links

If you need more information about these topics, you can follow these links:

History

  • 12 July, 2011: UsersDb_Log.LDF has been deleted as it was corrupt. Re-attaching the database solves the problem. The SQL script for the database is included as well, just in case it doesn't work. If creating database from script, the user needs to input a few values before using the system. (A lot of users complained that the log file was corrupt. Removing the previous LDF and re-attaching the new one works.)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

okdone
Web Developer
Singapore Singapore
Member
Programming is my hobby (and luckily my profession as well). My curiosity with computers started since early school days which inspired me to join computer hardware and even electronics repairs. The same interest made me choose Computer Science & Engineering as major in B.Tech. After a start with Java at college curriculum & teaching C programming for some time, I found the opportunity to work in C# and Asp.Net. I also like to study PHP, JSP-Struts and C etc. though my affair with Asp.Net, C# has been everlasting. I like to learn everything related to web - HTML, CSS, Javascript, JQuery and Photoshop etc.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Layout  Per page   
QuestionError in the codememberAtul Dhimaan5 Nov '12 - 1:57 
Hi i am facing one error for this .
It is always showing me error of database
 
In this method :
private static void EnsureValidMdbFile(string fileName)
      {
            SqlConnection conn = null;
            string constrrr = s_connPrefix + fileName;
            try
            {
                  conn = new SqlConnection(constrrr);
                  conn.Open();
            }
            catch(Exception ex)
            {
                  t<b>hrow new Exception("AccessFile is not valid: ",ex);</b>
            }
            finally
            {
                  if (conn != null)
                        conn.Close();
            }
      }
 
error is
AccessFile is not valid:
 

 
Regards,
Atul Dhiman.
atul-dhiman.blogspot.in
AnswerRe: Error in the codememberokdone5 Nov '12 - 2:31 
Hi,
 
The error is most definitely occuring because SQL Server is not able to attach the database file. Here are possible solutions-
 
-Rename the database file in connection string.
-Rather better approach is to use the script provided above (also can be found in comments below) to create a database and necessary schema. Then change your connectionstring in your web.config to point to the created database.
-If you are having error in attaching database. Please delete the file "UsersDb_log.LDF" and re-attach. It will generate a fresh log file for you. That should fix the issue. The database is OK, the Log File is corrupted.
 
A better appreciated suggestion will be to use the code in following article:-
Extending ASP.NET role based Security with Custom Security Module (Permission Based, Page Level Authorization)[^]
Above article approaches the same task in a relatively more organized way.
 
Hope that helps. If you're still facing difficulty, please reply with the specific error details so that it will be easier to suggest solution.
 
Best Regards,
okdone

QuestionOverall this article is greatmemberadeel198111 Mar '12 - 1:44 
This article is very good in term of thorough demonstration of almost many things which intermediate/expert level developers needed.Wouldn't have been better to check the code completey before uploading to this site.I had problems with 2 more posts where I coded 1000's lines and came up with classes missing.Otherwise this site seems to be the best among others.Take my criticism in a +ve sense Smile | :)
 
Always believe in God and never let misfortunes make you give up
AnswerRe: Overall this article is greatmemberokdone11 Mar '12 - 8:04 
Hello Adeel1981,
 
Thanks very much for your feedback. Please note that this article has been posted quite a long time back. Still as far as I remember the code has been working OKay with some of the amendments suggested in the discussion below. I didn't updated it for a long time in the view that many of proper and complete provider implementations are already available online. The purpose of this article is to explain an attempt to achieve access control over individual files.
 
Please note that this is supposed to be a test/demo project and hence needs to be properly tested before using it in production environment.
 
Moreover, if you are looking for flexible Permission based security, please do check out my article here:-
Extending ASP.NET role based Security with Custom Security Module (Permission Based, Page Level Authorization)[^]
 
In this article, the Permission based access to individual website resources is achieved through an httpmodule.
 
A working version of these providers and modules is used in following project:-

[^]
 
Thanks & Regards,
Amit
okdone

QuestionWhere is AccessConnectionHolder Class?memberadeel198111 Mar '12 - 1:37 
Where is AccessConnectionHolder Class and there are some methods which a4re use in static class without the static specifier which gives error.Kindly review the code again as some more things are needed to be done
 
Always believe in God and never let misfortunes make you give up
AnswerRe: Where is AccessConnectionHolder Class?memberokdone11 Mar '12 - 8:16 
Go to App_Code\MyConnectionHelper.cs file. There you'll find :-
 
internal sealed class AccessConnectionHolder
{....
...
}
okdone

QuestionCustom Membership over web/wcf servicememberE! Ray K18 Aug '11 - 6:51 
Hi,
 
You have provided a partial solution to my problem at hand. There's a central database hosting all the user credential for many ASP.net web applications. The authentication is perform over web/wcf services, the services will use custom membership to manage all the user credential. Do you have any idea how I can expose the custom membership over the web/wcf service???
Go with the flow...

AnswerRe: Custom Membership over web/wcf servicememberokdone19 Aug '11 - 4:31 
Hello,
 
I would definitely like to help in this regard. However, I would like to know which service you would be interested in exposing. Basically-
1. Membership Provider methods (Authentication section) (Authentication of users, retrieval of user information etc.) or
2. Role Provider methods (Authorization section )(User Roles and Role based Access etc) or
3. Would you like to do session sharing? (I am actually interested in this thing lately)
 
For the 1 & 2, you can definitely expose the required methods by creating wrapper services I think. Then those services can be consumed at the consumer end and sessions can be managed individually.
 
For the 3rd case, The authentication is always going to be at your application.   A session ID will be created and assigned to the user. All the other consumer applications will then authorize the user on the basis of this session ID. For this we can use the custom session mode and can write our own session providers. (Remember, it is a quite extensive and vulnerable approach). Here is some information about it. - (http://www.codeproject.com/KB/aspnet/ExploringSession.aspx)
 
However, if your solution primarily co-relates to content management, or controlling access to the content, U might be interested in some easy to learn, open source CMS like Umbraco Smile | :) Do let me know how it goes. Thanks
 
okdone
GeneralRe: Custom Membership over web/wcf servicememberE! Ray K19 Aug '11 - 9:14 
Hi,
 
Thank you for your detail reply.
 
Here's the breakdown of my solution. I have three projects under 1 solution.
 
Project 1: Web Services - this project exposes custom MembershipProvider and RoleProvider classes. The classes perform authentication and authorization using ASP.NET MembershipProvider. I added two web service classes to expose services provided by custom MembershipProvider and RoleProvider.
 
Project 2: Consumer - a simple web project calling the web service.
 
I am still working out the details of the implementation. Please give me some time before giving you a formal response. I can definitely share what I am trying to accomplish.
 
I will try to post more on this thread once after a few days.
 
thanks
Go with the flow...

GeneralRe: Custom Membership over web/wcf servicememberokdone21 Aug '11 - 22:25 
Hi,
 
That's great and definitely achievable I think. I think many articles at codeproject would be helpful for that. If the consumer is an asp.net client or normal Javascript client I hope one of my article also might help to point you in some directions here :- http://www.codeproject.com/KB/aspnet/jsonproxy-crossdomain.aspx . Hopefully you can share with us as a tutorial in codeproject - your experience with MemberShipProvider and RoleProvider wcf service and a sample client. Thanks
 
okdone

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 12 Jul 2011
Article Copyright 2007 by okdone
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid