Home » Asp.net

login pages without using Membership provider


I want to create a website that a user can logon and view their data. They should also be able to logout. I'm wondering how to achieve this WITHOUT using the Membership provider api provided by Microsoft. This is what I think should happen , please advise me if I'm incorrect.

1. user enters name and password and clicks button.

2.If username and password are correct the user is redirected to a webpage with their details.

3.A session is created.

4.The user logouts and the session is deleted.

Is this the way to go about it? If anyone has some similar code that I could reference that would be great


10 Answers Found


Answer 1

I love the Forms Authentication API for this. You do not need the Membership providers at all, just make a nice database that you approve of. I would probably encrypt the password data  if I were you maybe using MD5 hashing?

All you need to do is in your database for your DataType make the password  field type of NVARCHAR and a fairly large size to hash large passwords if you want.

In your code  behind make a hashing function like so:

using System.Web.Security;
using System.Text;
using System.Security.Cryptography;

private String hashPassword(string password)
    byte[] p = Encoding.UTF8.GetBytes(password);
    MD5 hasher = new MD5CryptoServiceProvider();
    return Encoding.UTF8.GetString(hasher.ComputeHash(p));

Note to add the using statements at the top of your file if your using CSharp.

Then after you authenticate against the database however you want, just simply do...

FormsAuthentication.SetAuthCookie(UserNameHere, true); // true if you want a persistent cookie "remember me functionality"

That does all the work for you, and you can STILL use the if (User.Identity.IsAuthenticated) etc...




Answer 2

Thanks. I'm a bit confused about the code. I don't see any code  that checks the database. Are you using the login  control or just a textbox etc.. ?


Answer 3

I didn't provide any code  for authenticating the user. That is up to you based on your authentication criteria. All I showed you was how to create  the cookie necessary for ASP.NET authentication AFTER you have authetnicated the user  against your own database, and I gave you a function on how to hash a password  in plain text into an MD5 hash.

If you want help writing queries against the database for authentication then I'd need to know more about your user tables and if you are using raw SQL or if you are using LINQ etc.. 


Answer 4

That's fine. I'm good with the sql. thanks


Answer 5

Cool stuff, then just remember, the Login Control usin the standard membership  providers all it does is call the FormsAuthentication on its own anyway, so you can use the same thing, but with your own code. 


Answer 6

ACtually I'm not all good with the sql. What sql do I write to check it a username  and password  are correct? Pseudo sql if fine. thanks.

I guess I could use something like:

select username from table where username = textbox1.text

select password from table where password = textbox2.text

If username = textbox1.text and password = textbox2.text then authenticated ?


Answer 7

How are you connecting ot the database? Are you using LINQ or are you doing old fashiond ado.net? Or are you even using something cool like the SQL data  Source? 


Answer 8

Oh and some psudo sql code...

SELECT * FROM Users WHERE UserName = 'Username' AND password  = 'password' 


Answer 9

this is what I use when the user  clicks on my login  button

 Using MyConnection As New SqlConnection("Data Source=sxxxxx;Initial Catalog=xxxx ;Persist Security Info=True;User ID=xxx;Password=xxx")
            Dim MyCommand As New SqlCommand("select username,password from table where username  = @input", MyConnection)
            MyCommand.Parameters.Add("@location", SqlDbType.NVarChar).Value = e.PostBackValue
            Dim r As SqlDataReader = MyCommand.ExecuteReader()
            GridView1.DataSource = r
            Label2.Visible = True
            lblCounty.Text = e.PostBackValue
            lblCounty.Visible = True
            Label1.Visible = True
            lblresults.Visible = True
            Label1.Text = GridView1.Rows.Count
        End Using


Answer 10

ok so yeah just add on to your command "select username, password, from table where username = @input and password = @passInput

then just feed it your parameters from your textbox. 




I want to create a website that a user can logon and view their data. They should also be able to logout. I'm wondering how to achieve this WITHOUT using the Membership provider api provided by Microsoft. This is what I think should happen , please advise me if I'm incorrect.

1. user enters name and password and clicks button.

2.If username and password are correct the user is redirected to a webpage with their details.

3.A session is created.

4.The user logouts and the session is deleted.

Is this the way to go about it? If anyone has some similar code that I could reference that would be great



I have deployed my custommebrship assembly and role provider assembly in the sts web config , central admin web config  and current web appln web config 's. i have created a  dll which has  login control and in the sign_authenticate event i am creating the securitytoken.

when i establish a session using the security token created using the iissettings object, and  while tryibng to redirect to the   home page of the/landing page of the web appln am Getting access denied error. 

signInControl_Authenticate(object sender, AuthenticateEventArgs e)




e.Authenticated = true; //till this line  it worked success.

 base.RedirectToSuccessUrl(); //here it throws  :" Eror: access  denied "     current ly signed in user : myname sign is as   diuff. user


anybody knows how to overcome this , means authentication is  success, but authoriation didnt work.

 how can i get asuccessfull login to theweb appln/ siteccollection? in my role provder class i  have created my own roles

for user name: myname

role name:  Administrators, Contributor.

any help is appreciated







I have a problem with a login module in my website.

I use a membership provider custom on my website.

My login page is the default page. When I go in http://www.mywebsite.com  I see my login page.

When I try to connect with my user and password, I'm not redirect to my url destination and reload the login page.

If I go in the url : http://www.mywebsite.com/login.aspx  (my login page), and write my user and password, it's done.

Are you a idea of my problem ?

I use Visual Studio 2010 with framework 4.0, and IIS 7.5

Thanks for your help.





Hope this is in the correct section (think it falls under setup/administration).

Currently in the design stage of a SharePoint 2010 project. When completed, this SharePoint application will run in a hosted environment with all users logging in via Forms Based Authentication (FBA) using Claims Authentication.

In our test environment I have done a few proof of concepts. I have customised the login screen and have created a custom profile membership provider. In addition to this I have created a webpart for adding and maintaining users. I have set up two web applications on the same server, one using FBA with SQL, the other using FBA with AD. The same code works with both (which is great) and so far is working as I hoped it would.

Question - on the surface both options (AD or SQL) seem to work the same, so does anyone have any recommendation/suggestions/experiences/gotchas that would help me decide which option to use. The administrators of the system will use the webpart to add/maintain users so AD or SQL knowledge is not important for them (either way it will appear the same). I have lots of experience with SQLMembership providers in the previous projects so my gut feeling is to go with that. Any thoughts or experiences would be appreciated.


What do you think about an ability of having multiple logins and login types to be attached to the same user? Let me explain this by showing how database schema can be re-factored to support this model:

Remove [Password], [PasswordSalt] columns from [Users] database tableAdd [Logins] table with one-to-many relationship between [Users] and [Logins] tables

This will allow one user to have multiple credentials attached to his or her account of different types such as Username&Password, Windows Live ID, Open ID from different providers

You will be able to restrict allowed login types and OpenID providers in web.config 

So.. do you think it is a good idea to add support of this model into ASP.NET 4.5/5.0 membership service?



Hi all,

I am using the .net membership provider, and I can get past the membership.validate user ok and into my secure page.


The problem I have is that when I reach the secured page, I have a login status control which isn't changing from login to logout.


Below is my login code:

If Membership.ValidateUser(txtUsername.Text, txtPassword.Text) Then
            If chkRememberMe.Checked Then
                FormsAuthentication.SetAuthCookie(txtUsername.Text, True)
                FormsAuthentication.SetAuthCookie(txtUsername.Text, False)
            End If
            lblLoginStatus.Text = "Oops! Login not found!"
        End If


 Thanks in advance.


I am working on implementing a custom membership provider that works against an existing schema in my database and have a few thoughts/question.

The login control will automatically call the ValidateUser method of the membership provider, so no matter how I implement the provider the only thing the login control cares about the bool value returned by this method.  What I am confused about is there could be numerous reasons why a login attempt failed; user is locked out, too many tries in a period of time, etc.  There is no way that I see to convey that to the control so it could display the proper message.  Other properties of the membership provider such as PasswordStrengthRegularExpression have absolutely no effect on the login control as well (out of the box), I would have hoped that it would automatically somehow translate into regular expression validators, but that doesn't seem to be the case.  So it seems that I need to initialize the login control properties with these settings out of the provider configuration if I want them to take on the control itself.

If the only thing that the Login control does out of the box (without manually handling events and doing the initialization as described above) is call the ValidateUser method on the membership provider, I see no way to convey back to the Login control why the validation failed or even doing things like throttling the validation requests based on a certain time window.  Ultimately my question is why would I even use the membership provider then in conjunction with the login control?  It seems like it was only designed for a Yes/No type response, which is very restrictive.  If I want to build in logic with different messages back to the user I need to handle the login control events and call my own authentication classes that will handle all of my business requirements as well as return a custom error message back to the Login control to display to the user so they know why their attempt is invalid.

Unless I am wrong in my assumptions, it seems that the interface between the Login control as the membership API is too restrictive to be useful.  Perhaps the API works better for other auth controls like ChangePassword better but for the actual Login control I don't see the point.

I appreciate your thoughts.


Hi Experts,

I am in the process of deploying an website developed in ASPNet 2.0 and using the login control and membership provider features. The site was deployed fine and was working perfectly till I changed the database name and user name to access the database. I changed the accordingly in the web.config to point to the new database. Everyting is working file except when the user tries to login into the website.

The error log says that login failed because it is trying to open the old database.

Any idea how I can solve the issue? Thanks for your help.





I have an Employee class in my App_Code folder.  On my login page I am trying to create an Employee using the asp.net username as a parameter in my Employee constructor.

 I have tried creating the employee in the page load event when it is a post back.  I have tried doing it in the Login1_LoggedIn event.  For some reason I cannot pull the username in either one of these places, but if I redirect after logging in and do the same thing on another page, it works.

How can I get it done on the login page?


  Dim em As Employee

        em = New Employee(CInt(Membership.GetUser().UserName))



hi, I am implementing my custom membership provider for MYSQL for this I write thi code:

public class CustomSqlMembershipProvider :MySQLMembershipProvider


   public override void Initialize(string name, NameValueCollection configs)


base.Initialize(name, configs);



When I am compiling this class, getting an error: 'Project.Models.CustomSqlMembershipProvider': cannot derive from sealed type 'MySql.Web.Security.MySQLMembershipProvider' C:\Workarea\\Project\Models\CustomSqlMembershipProvider.cs Why I getting this error. I have added the MySql.web and MySql.Data assembly references thanks in advance Aayushi


I am using Visual Studio 2008 Express and created a login page using the ASP.net web site Adminstration tool security to generate users and passwords.

After login, a new page appears.   I have a button to go back to the login page to allow a user to relogin.   When I try loging in again as a different user or the same, I get an error saying the resource that I am looing for was not available.

Can some one please help me ?  

I have a button on the page after login (one this one page will occur) and I am using on on click event to do the following:





After clicking on this button, the Login page appears again.  How can I release everyting to allow it to work like when I first open the application.

Thank You,

With our Silverlight application we currently have a custom ASP.NET Membership provider and works fine until we are tying to move to the cloud.. I have not seen  much on custom providers in general and was wondering if they even work in the Azure Platform..  Thanks.. 

I want personalize the mensagem who appears when user digit the wrong password. I wish put one message for each error Example: (User not found),(Password wrong);


I have setup my windows form application to use the ASP.NET membership and role manager.  My next step is to have the profile built into this, I have the custom Table Profile Provider and I don't know how I can get it to work on my form application, here is the code I added to my app.config, what do I have to do next?


  <profile defaultProvider="TableProfileProvider">
    <add name="TableProfileProvider" type="SqlTableProfileProvider" connectionStringName="TestingConnection" table="CustomProfile" applicationName="/"/>
    <add name="StoredProcedureProfileProvider" type="SqlStoredProcedureProfileProvider" connectionStringName="TestingConnection" setProcedure="setCustomProfileData" readProcedure="getCustomProfileData" applicationName="/"/>
    <add name="FirstName" type="string" defaultValue="[null]" customProviderData="FirstName;nvarchar;true"/>
    <add name="LastName" type="string" defaultValue="[null]" customProviderData="LastName;nvarchar;true"/>


My WCF service use SQL Membership provider to Authenticate user if authentication false it give exception like

"System.ServiceModel.Security.MessageSecurityException: An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail. ---> System.ServiceModel.FaultException: At least one security token in the message could not be validated"

I want to customise it to like "Login Failed:Anuthorized user."

guide me to how to create such custome fault message in my service..


Hi All,

I am trying to implement Forms Authentication in MOSS 2007. I need to use my exisitng SQL DB for validating the credentials. Any idea of how to implement this? Any example code/article would help.

Thanks in advance!

 Update: I was able to succesfully implement it with default Membership provider for testing by creating a new DB using aspnet_sql.exe but I need to use my exisiting SQL DB for validating credentials. Also we have one WCF service that is exposed so that every application uses that WCF service for validating credentials. So in my case I am trying to implement FBA in MOSS 2007 using WCF service for validating credentials.



Deal all,

now am working in web site that created by SP 2010 for sign in and sing up i use FBA with AD LDS

i already Create web applicatine in SharePoint 2010 with authontication setting FBA

and i configered AD LDS in my machine

but i need to know how to create membership provider then link between FBA and LDS 

i use this link 

george khalil's everything IT: AD LDS, SharePoint and Forms Based Authentication

but still not working

thanks in advanced



Hi all,

I have written a custom membership provider. There are some users in. I want to give access rights to this users to some sharepoint objects. How can I do this by code? How can I access or address such a user object in my custom membership provider?



We are having a problem with our Custom membership provider in SP2010 RTM. The membership provider worked well with SP2010 beta2, but we are not able to get it to work in RTM.

According to the blog below the syntax for querying users is different when you’re using claims based authentication.


Previously in beta2 we used the following syntax when querying users:

loginName = <customMembershipProvider>:<username> (e.g. myMembershipProvider:jon@hotmail.com)

And then we added the user if it didn't exist: web.SiteUsers.Add(loginName, email, name, notes);

In RTM, this doesn't work. We keep getting the 'User cannot be found'-error. Do we have to use the “i:0#.f|providername|username-format or something else?What does the i:0#.f mean?

Some details about the setup:

Windows server 2008R2, SQL 2008, Sharepoint 2010 RTM using local account (no AD).   

Any help appreciated!


Hi, i have been playing around with the membership provider model for the last week and have it got it working with a basic table schema.  The trouble i have is that i wish to add an additional field (eg First Name) but am not sure how i can do this.  Here's what i have so far:

 public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        MembershipUser user = new MembershipUser(Name, username, providerUserKey, email, passwordQuestion, null, isApproved, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now);
        db.AddParameter("@UID", username);
        db.AddParameter("@PWD", password);
        db.AddParameter("@EMAIL", email);
        db.AddParameter("@ISACTIVE", (isApproved == true ? "Y" : "N"));
        int i = db.ExecuteNonQuery(sql);

        if (i > 0)
            status = MembershipCreateStatus.Success;
            return user;
            status = MembershipCreateStatus.ProviderError;
            return null;


    public override void UpdateUser(MembershipUser user)
        db.AddParameter("@EMAIL", user.Email);
        db.AddParameter("@ISACTIVE", (user.IsApproved ? "Y" : "N"));
        db.AddParameter("@UID", user.UserName);
        int i = db.ExecuteNonQuery(sql);

    public override MembershipUser GetUser(string username, bool userIsOnline)
        MembershipUser user = null;
        db.AddParameter("@UID", username);
        SqlDataReader reader = (SqlDataReader)db.ExecuteReader(sql);
        while (reader.Read())
            user = new MembershipUser(Name, reader.GetString(reader.GetOrdinal("username")), null, reader.GetString(reader.GetOrdinal("email")), null, null, (reader.GetString(reader.GetOrdinal("isactive")) == "Y" ? true : false), false, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue);
        return user;

The trouble i have is that the CreateUser method expects a fixed number of arguments so if i add a new field/attribute to my table then how do i add to this method to do the insert.  There is a similar problem with the GetUser and UpdateUser methods as they both inherit from the MembershipUser class.

Appreciate if someone could point in the direction of an article that has tackled this problem.  I have been googling all day without success.  One solution i thought was just to ignore these methods and create my own ones but then i don't benefit from some of the pre built server controls.

Sorry if my jargon is wrong but i'm new on this and would appreciate any help.



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure