Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

.NET 

[TUT] Advanced login system with MySQL and ASP.NET [HOWTO][VB.NET]

Before reading this: This is largely based on the fact that you followed my previous tutorial about setting up MySQL on the local computer and got that one working. In this tutorial we go a step further and integrate Forms Authentication (Thanks to H3x0S for the idea of taking this further) and also with a "remember me" feature.

Find the thread here: https://hackforums.net/showthread.php?tid=1210405


A little notice:
This tutorial is not going to be as in depth as the previous one. I will try and cut out and explain the main points but otherwise you are left alone with the source. This is done as I expect you to have some understanding of database workings from the last tutorial. Of course you are still free to ask any questions.


Now then you are ready, let me start to admit a small mistake I did in that last tutorial... Or well it's not a mistake in that tut, but in this it will be as we are going to use the old database. If you created one yourself (for the hardcore users as I said) I can say that I just forgot to set the id felt to AutoIncrement. If you did that, no prob.

Anyone else want that want to follow along should go into MySQL Workbench (or however they manage their database) and find the "netdb" from my last tutorial and set the id column of the table vbtest to Auto Increment. The steps are as follows in MySQL Workbench:

Login as usual (see last tut) -> Expand netdb -> Expand Tables -> Right click on vbtest -> Select "Alter table..." -> Goto "Columns" at the tabs at the bottom -> Check "AI" for the column id. -> Hit apply and apply again -> Close the window.

While you are at it, you might want to delete any old users of the vbtest table as we are going to add a salt this time (the old ones won't be valid) :
Right click table -> Edit Table Data -> Select all the data -> Rightclick -> Delete Row(s) -> And hit the "Apply changes to data" in the small toolbar right over the "editor" -> Apply -> Finish.

NOW THE ACTUAL TUTORIAL CONTENTS IS COMING!

Table of contents
  • How can we improve from last time?

  • What is Forms Authentication?

  • Bonus info

  • Download

  • Final notes



How can we improve from last time?

Last time the goal was to make a clear tutorial about using MySQL with .NET. I did that, you properly read it and it's all nice and that.

But the goal was not to make a login system even though I used that as an example. The system worked and was secure against SQL injections. But it lacked some features if you want to have it really nice.

In fact I wasn't even going to make a login system as I find it kinda boring and I thought it was done a lot of times before.
But H3x0S wrote a comment and said that people properly would find it useful, and as I love helping others out and couldn't find that much on the subject. Why not write a tut.

Anyway, to get back to the content of this article/tutorial.

To be a useful loginsystem it actually needs to authenticate people not just validate their passwords and redirect them.

It also needs (in my opinion) a "remember me" feature. That should however be discarded in high security environments but that's not our concern right now.

It should have some kind of security. In our case the database was already hashed, but now we will store the hashes as salted hashes so they are not as easy to bruteforce. This doesn't really work if the attacker knows the salt, but if we imagine he only got access of a "sample" from the database it will be nice to have this extra layer of protection. Also if he tries to insert his own user with a SHA256 of his own password he will still get rejected as it's get checked against the SHA256 hash of the password he submits + our hash.

We will also hash our "remember me" cookies with an extra hash for added security.

What is Forms Authentication?

If you ask Wikipedia it's like this:
http://en.wikipedia.org/wiki/Form-based_authentication

A way of authenticating users trough HTTP Forms (as most websites do now a days) and not by using the standard HTTP Authentication system.

This is of course completely right, BUT in ASP.NET this is so much more.

ASP.NET provides of with a complete Forms authentication system where we only need to worry about validating the users credentials and then, that's it. Using the web.config file we can restrict our whole website, so no matter if it's an image, a css file, or an ASP file, it all ends up needing a valid user logged onto the system.

And it is really straight forward. Just see this example:
Code
'Creates a new FormsAuthenticationTicket.
Dim ticket As New Web.Security.FormsAuthenticationTicket("HSPSoftware", False, 10)
'Creates the actual cookie to contain the ticket
Dim ticketCookie As New Web.HttpCookie(Web.Security.FormsAuthentication.FormsCookieName, Web.Security.FormsAuthentication.Encrypt(ticket))
'Saves the cookie where the formauthenticationsystem is looking for it
ticketCookie.Path = Web.Security.FormsAuthentication.FormsCookiePath
'And finally sends it back to the client
Response.Cookies.Add(ticketCookie)

In this small piece of code we make a new ticket for the user "HSPSoftware" and set it to timeout after 10 minutes, and also the false property means that the ticket won't "survive" a browser restart.

Then we add it to a normal cookie and let's the FormsAuthentication system decide the name of that cookie and where it should be stored. And then we send the cookie containing our ticket back to the client.

Now we only need to add this to our web.config file:
Code
<system.web>
  [b]<!--[/b] This applies to everything (Except the exlusions later on) and locks down your whole site. -->
  <authentication mode="Forms">
  <forms name=".HSPLogin" loginUrl="Default.aspx" protection="All" path="/" timeout="10" />
  </authentication>
  [b]<!--[/b] Makges it so that anonomys users can't access the site -->
  <authorization>
  <deny users ="?" />
  <allow users = "*" />
  </authorization>
    </system.web>

This
does so that the whole site is locked down except Default.aspx which is going to serve as our login page together with Login.aspx.

If anyone who are not logged in tried to go to any other direct url they are redirected to Default.aspx to authenticate.

To store our style.css file and if you had some other files you can allow a file or a directory for everyone like this:

Code
<location path="NoProtection">
    <system.web>
  <authorization>
  <allow users ="*" />
  </authorization>
    </system.web>
  </location>

You will see all this demonstrated in the demo project attached to this.

UPDATE!!!!
Again big thanks to H3x0S, this time for pointing out that I forgot something really important in my sleepy coding trance.
While talking about Forms Authentication in .NET you can't really leave out "roles". This allows you to assign "roles" to each ticket that you store while authenticating the user
and then use these roles to grant and deny access to the user throughout the site (in an easy manner).

Sorry if some of the things I'm writing now isn't making any sense. I'm pretty dizzy. Anyway.

To make the role based system work, go into your favourite SQL manager and do as you also (properly) did earlier, alter the vbtest table inside the netdb database.
This time just add a new column and call it "roles"... Set the type to "varchar(255)". And that's all.

You will also see that the CreateUser.aspx file I included in the project has been "upgraded" with the role system. Now you can write roles seperated by ";" and then see what happens. For example you can only access "AboveTopSecret.aspx" if you are member of the group / have the role "HFUser"... And if you set yourself to "HFUser" and/or "admin" you will see some messages under the secret picture on SecretPage.aspx.

If you wonder how this is done, take a look inside "Global.asax" where I've set some code to grap the ticket each time a user authenticates his/her request. This ticket is then put into the current user object so the rest of the site knows all privileges of the user. And don't worry about people changing them, the cookies are encrypted by the servers machine key.

I don't really want to write more about it right now, you can take a look at the source if you want to... Otherwise just ask and I will be more specific.

Download the updated version under the original! :)
END OF UPDATE

Bonus info

For easy configuration you will see me refer to:
Code
System.Configuration.ConfigurationManager.AppSettings("something")

This is a neat, often underrated and underused, little trick to store static configuration information globally.

Inside my web.config file I have this (inside the configuration tag of course):
Code
<appSettings>
    <add key="something" value="HackForums are awesome!" />
  </appSettings>

Now I can retrieve the string "HackForums are awesome!" with the previous code anywhere on the website.

You will also see me do this inside my Default.aspx

Code
If Not Request.QueryString("error") Is Nothing Then
    Response.Write("<span id=""error"">")
    Select Case Request.QueryString("error")
    Case "0"
    Response.Write("You must fill out both fields!")
    Case "1"
    Response.Write("The username / password combination does not exist!")
    Case "2"
    Response.Write("Invalid cookie! I've deleted it for you!")
    End Select
    Response.Write("</span><br /><br />")
  End If

This is (I'm sorry to say) not all that common practice. Most scripts use something like this.

Code
If Not Request.QueryString("error") Is Nothing Then
    Response.Write("<span id=""error"">")
    Response.Write(Request.QueryString("error"))
    Response.Write("</span><br /><br />")
  End If

What is the problem with that you might ask? It looks way simpler and with cleaner URL's to me...

Well... What if I sent a tinyurl link around with your website which send users to something like:

Code
http://www.yoursite.com/Default.aspx?error=<script type="text/javascript">Alert("You just got hijacked!")</script>

As you might read from the link above. You would just get hijacked. Congratulations you just fallen victim for Cross Site Scripting or most often referred to as XSS. What if I loaded some script from some server to send your users logins to me while submitting? Maybe the nerds would see the code and think WTF but are you sure that normal users also would do that? Are you sure that your mom knows how to spot an XSS attack?

Better be safe! ;)

Download:

Here is the download link for the complete project. Remember to open to web.config file and set your own database credentials and also set your own salts if you intend to use it for something "real".

http://www.sendspace.com/file/tvi6l9


Once again sorry for that crappy file host but everywhere else is still complaining about "IO Error".

And here are the updated version which includes "roles" ... Be sure to read the thing with "UPDATE" at the top of the article (or somewhere like that) to see what needs to be done (you will need to add a single column to your table).

http://www.sendspace.com/file/5sggxz

EDIT:
I forgot this... Inside the "NoProtection" folder is a file called CreateUser.aspx. Open this url in your browser and you can create test users with the correct hashed passwords. This also serves to show you how to create users. But this file should of course NOT make it into production!!!

Final notes

This time I wasn't so in depth as last time. It's, as I wrote earlier, because I expect you to at least have some basic understanding of the code. It's all right if you just leech the code anyway, but if you want to follow to tutorial you must at least try and get into the fight a little.

If it's still to hard for someone out there, don't be shy. I don't bite, just leave a comment and I will get back to you as soon as possible.

But most important of all!!!
Remember to say thanks!
- No seriously, I don't hate people who leech... I hate people leeching without leaving a comment 😵

That's all for now! 🤝

Bookmarked, keep up with these beast tutorials ^^
μεγαλομανία
(Apr 14, 2011 12:40 PM)Ethereal Wrote:  Bookmarked, keep up with these beast tutorials ^^

Thanks Ethereal!😊

I will do my best.
Very good tutorial! Please use SQL Server for the next tutorial because it's better to use it over MySQL since it is much easier to work with it in ASP.NET because it's very well supported. Also, you didn't provide more information about roles and that is very important. Especially the multi-roles system for pages with Administration Panel...Add that to this tutorial. If I catch some time I will write few tutorials about ASP.NET.
(Apr 14, 2011 01:23 PM)H3x0S Wrote:  Very good tutorial! Please use SQL Server for the next tutorial because it's better to use it over MySQL since it is much easier to work with it in ASP.NET because it's very well supported. Also, you didn't provide more information about roles and that is very important. Especially the multi-roles system for pages with Administration Panel...Add that to this tutorial. If I catch some time I will write few tutorials about ASP.NET.

Aaarh I forgot all about that. I'm actually more of a PHP man.

That's also why I choose MySQL.

Oh and MSSQl don't want to run on my computer at all really? It's an I7 processor + 4 gigs of ram. And it's nowhere near utilizing it all, but MS SQL just don't want to work with me.

Would it be all right if I did it with Access as it's about the same thing? (at least while doing the "common stuff" ^^)

---- Forgot to say ----
But if you can do it better, feel free to do it! And that's by no means offensive! That's more like a request or something (I don't know the correct English word, so sorry if that didn't make to much sense)...
(Apr 14, 2011 01:28 PM)HSPSoftware Wrote:  Aaarh I forgot all about that. I'm actually more of a PHP man.

That's also why I choose MySQL.

Oh and MSSQl don't want to run on my computer at all really? It's an I7 processor + 4 gigs of ram. And it's nowhere near utilizing it all, but MS SQL just don't want to work with me.

Would it be all right if I did it with Access as it's about the same thing? (at least while doing the "common stuff" ^^)

---- Forgot to say ----
But if you can do it better, feel free to do it! And that's by no means offensive! That's more like a request or something (I don't know the correct English word, so sorry if that didn't make to much sense)...

How do you mean it won't run? What happens when you try to run a MSSQL powered website?
(Apr 14, 2011 01:35 PM)H3x0S Wrote:  How do you mean it won't run? What happens when you try to run a MSSQL powered website?

The installation Wizard crashes... And it's REALLY slow and sluggish. Nothing else on my computer is that. I'm by the way using Windows 7 64bit and it is the 64bit version I'm using. But I might try using a VM or some dedicated database machine if you really want it that bad :)
(Apr 14, 2011 01:37 PM)HSPSoftware Wrote:  The installation Wizard crashes... And it's REALLY slow and sluggish. Nothing else on my computer is that. I'm by the way using Windows 7 64bit and it is the 64bit version I'm using. But I might try using a VM or some dedicated database machine if you really want it that bad :)

You don't have to install it because it comes with Microsoft Visual Web Developer. Just go to Project -> New Item... -> Data -> Sql Server Database.
(Apr 14, 2011 01:45 PM)H3x0S Wrote:  You don't have to install it because it comes with Microsoft Visual Web Developer. Just go to Project -> New Item... -> Data -> Sql Server Database.

What? o.O

I tried using windows server 2008 R2... Guess I should stick with my PHP xD

Anyway, isn't it optional to install? By the way I'm using Ultimate edition of 2010.

Now H3x0S.... I've updated the article and uploaded a new version of the source code. As I said, I'm pretty sleepy but I tested the code and it worked.

But just spam me with ideas for improvements, I love to make stuff like this ...
Thanks for sharing.
5 star ratings :)


Possibly Related Threads...
Thread / Author Replies Views Last Post
[.NET] by iconv32Jul 10, 2022 12:18 PM 0 214 Jul 10, 2022 12:18 PM
Last Post: iconv32
[C] by optionalMay 21, 2021 08:42 AM 7 310 May 21, 2021 08:42 AM
Last Post: Charger
[C#] by Jake JohnsonDec 10, 2020 09:25 AM 3 304 Dec 10, 2020 09:25 AM
Last Post: Xamarin