English 中文(简体)
ASP.NET WP - Security
  • 时间:2024-11-05

ASP.NET WP - Security


Previous Page Next Page  

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 cpck Next. This will install and configure the required packages.

Once the installation is finished then let’s run the apppcation 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 cpck on the Register pnk and you will see the following webpage in which you can register by providing the following information.

Register

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

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

@section Scripts {
   <script src = "~/Scripts/jquery.vapdate.min.js"></script>
   <script src = "~/Scripts/jquery.vapdate.unobtrusive.min.js"></script>
}
@{
   Layout = "~/_SiteLayout.cshtml";
   Page.Title = "Register";
   
   // Initiapze general page variables
   var email = "";
   var password = "";
   var confirmPassword = "";
   
   // Setup vapdation
   Vapdation.RequireField("email", "You must specify an email address.");
   Vapdation.RequireField("password", "Password cannot be blank.");
   Vapdation.Add("confirmPassword",
   Vapdator.EqualsTo("password", "Password and confirmation password do not match."));
   Vapdation.Add("password",
      Vapdator.StringLength(
         maxLength: Int32.MaxValue,
         minLength: 6,
         errorMessage: "Password must be at least 6 characters"));
   
   // If this is a POST request, vapdate and process data
   if (IsPost) {
      AntiForgery.Vapdate();
      email = Request.Form["email"];
      password = Request.Form["password"];
      confirmPassword = Request.Form["confirmPassword"];
      
      // Vapdate the user s captcha answer
      // if (!ReCaptcha.Vapdate("PRIVATE_KEY")) {
         // ModelState.AddError("recaptcha", "Captcha response was not correct");
      // }
     
      // If all information is vapd, create a new account
      if (Vapdation.IsVapd()) {
         // 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, 
                  requireEmailConfirmation);
               
               if (requireEmailConfirmation) {
                  var hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer,
                     UriFormat.Unescaped);
                  var confirmationUrl = hostUrl + VirtualPathUtipty.ToAbsolute
                     ("~/Account/Confirm?confirmationCode = " 
                     + HttpUtipty.UrlEncode(token));
                  WebMail.Send(
                     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
                  Response.Redirect("~/Account/Thanks");
               } else {
                  // Navigate back to the homepage and exit
                  WebSecurity.Login(email, password);
                  Response.Redirect("~/");
               }
            }catch (System.Web.Security.MembershipCreateUserException e) {
               ModelState.AddFormError(e.Message);
            }
         } else {
            // User already exists
            ModelState.AddFormError("Email address is already in use.");
         }
      }
   }
}

<hgroup class = "title">
   <h1>@Page.Title.</h1>
   <h2>Create a new account.</h2>
</hgroup>

<form method = "post">
   @AntiForgery.GetHtml()
   @* If at least one vapdation error exists, notify the user *@
   @Html.VapdationSummary("Account creation was unsuccessful. 
      Please correct the errors and try again.", 
      excludeFieldErrors: true, htmlAttributes: null)
   
   <fieldset>
      <legend>Registration Form</legend>
      <ol>
         <p class = "email">
            <label for = "email" @if(!ModelState.IsVapdField("email")){
               <text>class = "error-label"</text>}>Email address</label>
            <input type = "text" id = "email" name = "email" value = "@email"   
               @Vapdation.For("email") />
            
            @* Write any email vapdation errors to the page *@
            @Html.VapdationMessage("email")
         </p>
         
         <p class = "password">
            <label for = "password" @if(!ModelState.IsVapdField("password")) {<text>
               class = "error-label"</text>}>Password</label>
            <input type = "password" id = "password" name = "password"
               @Vapdation.For("password") />
            
            @* Write any password vapdation errors to the page *@
            @Html.VapdationMessage("password")
         </p>
         
         <p class = "confirm-password">
            <label for = "confirmPassword" 
               @if(!ModelState.IsVapdField("confirmPassword")) 
               {<text>class = "error-label"</text>}>Confirm password</label>
            <input type = "password" id = "confirmPassword" name = "confirmPassword"
               @Vapdation.For("confirmPassword") />
            
            @* Write any password vapdation errors to the page *@
            @Html.VapdationMessage("confirmPassword")
         </p>
         
         <p class = "recaptcha">
            <span class = "message-info">
               <p>
                  To enable CAPTCHA verification, <a href = 
                  "http://go.microsoft.com/fwpnk/?LinkId=204140">install the
                  ASP.NET Web Helpers Library</a> and uncomment ReCaptcha.GetHtml 
                  and replace  PUBLIC_KEY  with your pubpc key. At the top of this 
                  page, uncomment ReCaptcha. Vapdate and replace  PRIVATE_KEY  with 
                  your private key.Register for reCAPTCHA keys at <a href = 
                  "http://recaptcha.net"> reCAPTCHA.net</a>.
               </p>
            </span>
            @*
               @ReCaptcha.GetHtml("PUBLIC_KEY", theme: "white")
               @Html.VapdationMessage("recaptcha")
            *@
         </p>
      </ol>
      <input type = "submit" value = "Register" />
      
   </fieldset>
</form>

When you cpck 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.

Logo

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) {
   Response.Redirect("~/Account/Login");
}
@{
   Layout = "~/_SiteLayout.cshtml";
   Page.Title = "About My Site";
}

<hgroup class = "title">
   <h1>@Page.Title.</h1>
   <h2>Your app description page.</h2>
</hgroup>

<article>
   <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>
</article>

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

</aside>

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

Login Page

The user is not logged in as of now, so when you cpck on the About pnk 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 cpck on Log in and you will see the Home page.

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

About My Site Advertisements