ASP.NET WP - Security

In this chapter, we will be covering how to secure the website so that some of the pages are available only to people who log in. To secure your website you can make your website so that users can log into it. Securing your website can be useful for many reasons.

  • Your site might have pages that should be available only to members.

  • Sometimes you will require users to log in so that they can send feedback or leave a comment on your website.

  • If the users are not logged in then they can still browse some of the pages, but not all of them.

  • Users who are not logged in are known as anonymous users.

How to Secure a Website with Authentication?

A user will first need to register on your website and can then log in to the site. To register on the website, a user will need a username and an email address along with a password to confirm that a user is who they claim to be. This process of logging in and confirming a user's identity is known as authentication.

WebMatrix provides a built-in template known as Starter Site to create a website, which contains the following properties.

  • A database that can store user names and passwords for users.

  • A registration page where users can register.

  • A login/logout page.

  • A password recovery and reset page.

Let’s have a look into a simple example by creating a new Starter Site.

Site From Template

Enter SecurityDemo in the Site Name field and click Next. This will install and configure the required packages.

Once the installation is finished then let’s run the application and you will see the following web page.

Home Page

As you can see there are two buttons Register and Log in on the top right hand side of the page.

Let’s click on the Register link and you will see the following webpage in which you can register by providing the following information.


Here is the implementation Register.cshtml file which is under the Account folder on the site.

@* Remove this section if you are using bundling *@

@section Scripts {
   <script src = "~/Scripts/jquery.validate.min.js"></script>
   <script src = "~/Scripts/jquery.validate.unobtrusive.min.js"></script>
   Layout = "~/_SiteLayout.cshtml";
   Page.Title = "Register";
   // Initialize general page variables
   var email = "";
   var password = "";
   var confirmPassword = "";
   // Setup validation
   Validation.RequireField("email", "You must specify an email address.");
   Validation.RequireField("password", "Password cannot be blank.");
   Validator.EqualsTo("password", "Password and confirmation password do not match."));
         maxLength: Int32.MaxValue,
         minLength: 6,
         errorMessage: "Password must be at least 6 characters"));
   // If this is a POST request, validate and process data
   if (IsPost) {
      email = Request.Form["email"];
      password = Request.Form["password"];
      confirmPassword = Request.Form["confirmPassword"];
      // Validate the user's captcha answer
      // if (!ReCaptcha.Validate("PRIVATE_KEY")) {
         // ModelState.AddError("recaptcha", "Captcha response was not correct");
      // }
      // If all information is valid, create a new account
      if (Validation.IsValid()) {
         // Insert a new user into the database
         var db = Database.Open("StarterSite");
         // Check if user already exists
         var user = db.QuerySingle("SELECT Email FROM UserProfile WHERE LOWER(Email) =
            LOWER(@0)", email);
         if (user == null) {
            // Insert email into the profile table
            db.Execute("INSERT INTO UserProfile (Email) VALUES (@0)", email);
            // Create and associate a new entry in the membership database.
            // If successful, continue processing the request
            try {
               bool requireEmailConfirmation = !WebMail.SmtpServer.IsEmpty();
               var token = WebSecurity.CreateAccount(email, password, 
               if (requireEmailConfirmation) {
                  var hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer,
                  var confirmationUrl = hostUrl + VirtualPathUtility.ToAbsolute
                     ("~/Account/Confirm?confirmationCode = " 
                     + HttpUtility.UrlEncode(token));
                     to: email,
                     subject: "Please confirm your account",
                     body: "Your confirmation code is: " + token + ". 
                     Visit <a href = \"" + confirmationUrl + "\">" + 
                     confirmationUrl + "</a> to activate your account."
               if (requireEmailConfirmation) {
                  // Thank the user for registering and let them know an 
                     email is on its way
               } else {
                  // Navigate back to the homepage and exit
                  WebSecurity.Login(email, password);
            }catch (System.Web.Security.MembershipCreateUserException e) {
         } else {
            // User already exists
            ModelState.AddFormError("Email address is already in use.");

<hgroup class = "title">
   <h2>Create a new account.</h2>

<form method = "post">
   @* If at least one validation error exists, notify the user *@
   @Html.ValidationSummary("Account creation was unsuccessful. 
      Please correct the errors and try again.", 
      excludeFieldErrors: true, htmlAttributes: null)
      <legend>Registration Form</legend>
         <li class = "email">
            <label for = "email" @if(!ModelState.IsValidField("email")){
               <text>class = "error-label"</text>}>Email address</label>
            <input type = "text" id = "email" name = "email" value = "@email"   
               @Validation.For("email") />
            @* Write any email validation errors to the page *@
         <li class = "password">
            <label for = "password" @if(!ModelState.IsValidField("password")) {<text>
               class = "error-label"</text>}>Password</label>
            <input type = "password" id = "password" name = "password"
               @Validation.For("password") />
            @* Write any password validation errors to the page *@
         <li class = "confirm-password">
            <label for = "confirmPassword" 
               {<text>class = "error-label"</text>}>Confirm password</label>
            <input type = "password" id = "confirmPassword" name = "confirmPassword"
               @Validation.For("confirmPassword") />
            @* Write any password validation errors to the page *@
         <li class = "recaptcha">
            <div class = "message-info">
                  To enable CAPTCHA verification, <a href = 
                  "">install the
                  ASP.NET Web Helpers Library</a> and uncomment ReCaptcha.GetHtml 
                  and replace 'PUBLIC_KEY' with your public key. At the top of this 
                  page, uncomment ReCaptcha. Validate and replace 'PRIVATE_KEY' with 
                  your private key.Register for reCAPTCHA keys at <a href = 
               @ReCaptcha.GetHtml("PUBLIC_KEY", theme: "white")
      <input type = "submit" value = "Register" />

When you click on the Register button then you will see the Home page again, but you will see that now you are logged in by mentioning your email id.


Create Page for Members Only

In the website you will want some pages that can only be accessed by the members only. ASP.NET lets you configure pages so they can be accessed only by logged-in members. Typically, if anonymous users try to access a members-only page, you redirect them to the login page.

Let’s have a look into a simple example in which we modify the About page. When a user is logged in, then the user can access this page otherwise the user will be redirected to the login page. So let’s replace the following code in About.cshtml file.

@if (!WebSecurity.IsAuthenticated) {
   Layout = "~/_SiteLayout.cshtml";
   Page.Title = "About My Site";

<hgroup class = "title">
   <h2>Your app description page.</h2>

   <p>Use this area to provide additional information.</p>
   <p>Use this area to provide additional information.</p>
   <p>Use this area to provide additional information.</p>

   <h3>Aside Title</h3>
   <p>Use this area to provide additional information.</p>
      <li><a href = "~/">Home</a></li>
      <li><a href = "~/About">About</a></li>
      <li><a href = "~/Contact">Contact</a></li>


Let’s run the application and you will see the following Home page.

Login Page

The user is not logged in as of now, so when you click on the About link then you will see that you will directed to the login page as shown in the following screenshot.

Use Local Account

Let’s enter the credentials.

Login Local Account

Now click on Log in and you will see the Home page.

When you now click on the About link, you will see that About page is now accessible to you as shown in the following screenshot.

About My Site