Hi all, here's the quickest way to get forms authentication up and running in your asp.net web app, storing usernames and hashed password in your own database. First up, make a table in your database to store your users:
CREATE TABLE users(
        email [varchar](250)  NOT NULL,
        password [varchar](250) NOT NULL,
  CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED 
  (
    [email] ASC
  )
)
Then, edit your web.config like this (i've skipped the bits you don't need to change):
<configuration>
  <connectionStrings>
    <add name="Main" connectionString="uid=myuser; pwd=mypassword; Initial Catalog=mydatabase; Server=mydbserver" />
  </connectionStrings>

  <system.web>
    <authentication mode="Forms" />
    <authorization>
      <deny users="?" />
    </authorization>
  </system.web>

  <location path="Assets">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
</configuration>
The connection string is what we'll use to get access to our sql server. The 'authentication mode=forms' bit is what enables the forms auth mode. The 'deny users=?' is used so that people who haven't logged in will have no access. And the 'location path=assets' part is so that when you're not logged in, you'll still be able to see all the assets, eg your CSS, images, etc so that the login page doesn't look hideous. Next up, make a typical web form called Login.aspx, with the following controls in it somewhere:
<p>
  <strong>Email:</strong>
  <br />
  <asp:TextBox ID="txtUserName" runat="server" Columns=50></asp:TextBox>
</p>

<p>
  <strong>Password:</strong>
  <br />
  <asp:TextBox ID="txtUserPass" runat="server" Columns=50 TextMode="Password"></asp:TextBox>
</p>

<p>
  <asp:Button ID="bnLogon" runat="server" Text="Logon" />
  <br />
  <asp:Label id="lblMsg" ForeColor="red" runat="server" />
</p>
Go into design mode, and double click the logon button to make an event handler for it in the code-behind file. Your login.aspx.cs should look like this:
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.SqlClient;
using System.Security.Cryptography;

public partial class Login : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!String.IsNullOrEmpty(Request.Params["logout"]))
    {
      FormsAuthentication.SignOut();
      Response.Redirect("./");
    }
  }

  protected void bnLogon_Click(object sender, EventArgs e)
  {
    if (ValidateUser(txtUserName.Text, txtUserPass.Text))
      FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true);
    else
      lblMsg.Text = "Incorrect";
  }

  /// <summary>
  /// Filter out the fat fingers who get their passwords wrong
  /// </summary>
  bool ValidateUser(string user, string pass)
  {
    string connStr = ConfigurationManager.ConnectionStrings["Main"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(connStr))
    {
      conn.Open();
      string sql = "select email from users where email = @email and password = @password";
      SqlCommand cmd = new SqlCommand(sql, conn);
      cmd.Parameters.AddWithValue("@email", user);
      cmd.Parameters.AddWithValue("@password", Sha1(Salt(pass)));
      return cmd.ExecuteScalar() is string;
    }
  }

  /// <summary>
  /// Salt the hell out of a string before hashing it
  /// </summary>
  public string Salt(string text)
  {
    return
      "zu5QnKrH4NJfOgV2WWqV5Oc1l" +
      text +
      "1DMuByokGSDyFPQ0DbXd9rAgW";
  }

  /// <summary>
  /// One-way hash the password, so the DBA can't see the inevitable swear words in the password column
  /// </summary>
  public string Sha1(string text)
  {
    byte[] clear = Encoding.UTF8.GetBytes(text);
    byte[] hash = new SHA1CryptoServiceProvider().ComputeHash(clear);
    return BitConverter.ToString(hash).Replace("-", "").ToLower();
  }
}
Make sure you change the salt values above, just to make it your own. Now, in your master page you probably want somewhere on your page to show the current logged in name, and provide a logout link. For me, it looks like this:
<% if (Context.User.Identity.IsAuthenticated) { %>
  <%= Context.User.Identity.Name%>
  Log out
<% } %>
Ok we're done with it! But now you'll need to create at least one user in your database, and probably more. To create the hashed password, i used the following ruby script (make sure your salts are the same as what is in your login.aspx).
a="zu5QnKrH4NJfOgV2WWqV5Oc1l"
b="1DMuByokGSDyFPQ0DbXd9rAgW"
c=a + "my new password here" + b
require 'digest/sha1'
Digest::SHA1.hexdigest c
=> "e7f0df4d064a7d2cdc653447e752cf4d736e114b"
Now, you can put that value between the quites in your 'password' field in the database. Cheers!

Thanks for reading! And if you want to get in touch, I'd love to hear from you: chris.hulbert at gmail.

Chris Hulbert

(Comp Sci, Hons - UTS)

Software Developer (Freelancer / Contractor) in Australia.

I have worked at places such as Google, Cochlear, Assembly Payments, News Corp, Fox Sports, NineMSN, FetchTV, Coles, Woolworths, Trust Bank, and Westpac, among others. If you're looking for help developing an iOS app, drop me a line!

Get in touch:
[email protected]
github.com/chrishulbert
linkedin



 Subscribe via RSS