Click here to Skip to main content
15,888,454 members
Articles / Web Development / ASP.NET
Article

Membership and Role providers for MySQL

Rate me:
Please Sign up or sign in to vote.
4.86/5 (71 votes)
20 Dec 20051 min read 1M   5.8K   178   227
This article provides two files that contain a Membership Provider and a Role Provider for ASP.NET v2.0.

Introduction

This article provides two files that contain a Membership provider and a Role provider for ASP.NET v2.0.

Microsoft provides a Membership provider in the framework but only for SQL Server. The class does not seem to work for MySQL so I decided to write a new provider from the ODBC provider sample code included in the framework SDK.

How to use it

To use these classes, you will need the latest MySQL .NET Connector. You might need to recompile it with the new C# compiler for v2.0 (but the new framework should normally support v1.0 or 1.1 assemblies).

  1. Create the tables (note that these SQL commands might not work with MySQL 4).
    SQL
    CREATE TABLE Roles
    (
      Rolename Varchar (255) NOT NULL,
      ApplicationName varchar (255) NOT NULL
    )
    
    CREATE TABLE UsersInRoles
    (
      Username Varchar (255) NOT NULL,
      Rolename Varchar (255) NOT NULL,
      ApplicationName Text (255) NOT NULL
    )
    ALTER TABLE 'usersinroles' 
          ADD INDEX ( 'Username', 'Rolename', 'ApplicationName') ;
    ALTER TABLE 'roles' ADD INDEX ( 'Rolename' , 'ApplicationName' ) ;
    
    CREATE TABLE 'users' (
      'PKID' varchar(36) collate latin1_general_ci NOT NULL default '',
      'Username' varchar(255) collate latin1_general_ci NOT NULL default '',
      'ApplicationName' varchar(100) 
                        collate latin1_general_ci NOT NULL default '',
      'Email' varchar(100) collate latin1_general_ci NOT NULL default '',
      'Comment' varchar(255) collate latin1_general_ci default NULL,
      'Password' varchar(128) collate latin1_general_ci NOT NULL default '',
      'PasswordQuestion' varchar(255) collate latin1_general_ci default NULL,
      'PasswordAnswer' varchar(255) collate latin1_general_ci default NULL,
      'IsApproved' tinyint(1) default NULL,
      'LastActivityDate' datetime default NULL,
      'LastLoginDate' datetime default NULL,
      'LastPasswordChangedDate' datetime default NULL,
      'CreationDate' datetime default NULL,
      'IsOnLine' tinyint(1) default NULL,
      'IsLockedOut' tinyint(1) default NULL,
      'LastLockedOutDate' datetime default NULL,
      'FailedPasswordAttemptCount' int(11) default NULL,
      'FailedPasswordAttemptWindowStart' datetime default NULL,
      'FailedPasswordAnswerAttemptCount' int(11) default NULL,
      'FailedPasswordAnswerAttemptWindowStart' datetime default NULL,
      PRIMARY KEY  ('PKID')
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
  2. Change MySqlMembershipProvider::encryptionKey to a random hexadecimal value of your choice.
  3. Upload the two files to ~/App_Code.
  4. Modify your web.config using the following template (if you are on a shared hosting server, you will have to set writeExceptionsToEventLog to false):
    XML
    <connectionStrings>
        <add name="ConnString" 
          connectionString="Database=YOURDBNAME;Data Source=localhost;
                            User Id=YOURUSERNAME;Password=YOURPWD" />
    </connectionStrings>
    <system.web>
        <roleManager defaultProvider="MySqlRoleProvider"
            enabled="true"
            cacheRolesInCookie="true"
            cookieName=".ASPROLES"
            cookieTimeout="30"
            cookiePath="/"
            cookieRequireSSL="false"
            cookieSlidingExpiration="true"
            cookieProtection="All" >
        <providers>
            <clear />
            <add
                name="MySqlRoleProvider"
                type="Andri.Web.MySqlRoleProvider"
                connectionStringName="ConnString"
                applicationName="YOURAPPNAME"
                writeExceptionsToEventLog="true"
            />
        </providers>
        </roleManager>
        
        <membership defaultProvider="MySqlMembershipProvider" 
                    userIsOnlineTimeWindow="15">
            <providers>
                <clear />
                <add
                    name="MySqlMembershipProvider"
                    type="Andri.Web.MySqlMembershipProvider"
                    connectionStringName="ConnString"
                    applicationName="YOURAPPNAME"
                    enablePasswordRetrieval="false"
                    enablePasswordReset="true"
                    requiresQuestionAndAnswer="true"
                    requiresUniqueEmail="true"
                    passwordFormat="Hashed"
                    writeExceptionsToEventLog="true"
                />
          </providers>
        </membership>
    </system.web>
  5. That's it! You can use the login controls provided in the ASP.NET framework v2.0 if you want or use your own controls.

You can do whatever you want with this code but just send me an email if you have done some improvements or some bug correction. Isn't that what this website is about, sharing?

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
France France
I am a software developper working for a multinational, in the south of France.

Comments and Discussions

 
GeneralRe: New code doesn't work Pin
flaxx1-Dec-06 0:24
flaxx1-Dec-06 0:24 
GeneralRe: New code doesn't work Pin
flaxx14-Dec-06 6:09
flaxx14-Dec-06 6:09 
GeneralError Logging In/Out with Firefox Pin
josepaulino24-Sep-06 18:18
josepaulino24-Sep-06 18:18 
NewsNew updated code with bug fixes Pin
Rakotomalala Andriniaina6-Sep-06 10:40
Rakotomalala Andriniaina6-Sep-06 10:40 
GeneralIt's a good thinf that it works then Pin
EShy29-Sep-06 9:21
EShy29-Sep-06 9:21 
QuestionSample code on how to log in users [modified] Pin
SveinErik26-Aug-06 23:46
SveinErik26-Aug-06 23:46 
AnswerRe: Sample code on how to log in users Pin
Rakotomalala Andriniaina6-Sep-06 10:43
Rakotomalala Andriniaina6-Sep-06 10:43 
Questionerror connecting: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. [modified] Pin
wrighty17-Aug-06 10:39
wrighty17-Aug-06 10:39 
Has anyone experienced this problem using this membership provider for Mysql

Error is

error connecting: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: MySql.Data.MySqlClient.MySqlException: error connecting: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

I've got it running under an ASP.NET/VB.NET website with compiling as suggested ,but do get this error whenattempting to login into the website.

Once in all seems OK

Confused | :confused:

error connecting: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

The error points to line 1282 in MySQLMembershipProvider.cs

Line 1280: else
Line 1281: {
Line 1282: throw e;
Line 1283: }
Line 1284: }

Thanks



AnswerRe: error connecting: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. [modified] Pin
Rakotomalala Andriniaina6-Sep-06 10:45
Rakotomalala Andriniaina6-Sep-06 10:45 
QuestionWhy am I not showing as logged in? Pin
jhdoc815-Aug-06 13:19
jhdoc815-Aug-06 13:19 
QuestionMySQL .... Pin
thachvv181-Aug-06 23:42
thachvv181-Aug-06 23:42 
GeneralIs this user online Pin
paolo100021-Jul-06 3:33
paolo100021-Jul-06 3:33 
GeneralIssues in the web config not finding the class Pin
AlanSchneider10-Jul-06 10:56
AlanSchneider10-Jul-06 10:56 
AnswerRe: Issues in the web config not finding the class Pin
litograph6820-Mar-07 13:48
litograph6820-Mar-07 13:48 
GeneralRe: Issues in the web config not finding the class [modified] Pin
ayfaizal20-Mar-07 15:36
ayfaizal20-Mar-07 15:36 
GeneralCheking session Pin
Frehley9-Jul-06 13:27
Frehley9-Jul-06 13:27 
GeneralMySql Profile Provider [modified] Pin
Edacio23-Jun-06 10:10
Edacio23-Jun-06 10:10 
GeneralRe: MySql Profile Provider Pin
Edacio28-Jun-06 10:13
Edacio28-Jun-06 10:13 
GeneralAccess Denied Pin
bonfire8922-Jun-06 18:41
bonfire8922-Jun-06 18:41 
GeneralRe: Access Denied Pin
Rakotomalala Andriniaina6-Sep-06 10:59
Rakotomalala Andriniaina6-Sep-06 10:59 
Generalemail and password validation Pin
aldaran20-Jun-06 10:49
aldaran20-Jun-06 10:49 
GeneralRe: email and password validation Pin
Rakotomalala Andriniaina6-Sep-06 10:50
Rakotomalala Andriniaina6-Sep-06 10:50 
GeneralThanks!!! Pin
SleepyCrat16-Jun-06 7:02
SleepyCrat16-Jun-06 7:02 
QuestionProfile Provider ? Pin
tbp039-Jun-06 10:27
tbp039-Jun-06 10:27 
AnswerRe: Profile Provider ? Pin
Edacio28-Jun-06 10:13
Edacio28-Jun-06 10:13 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.