Sunday, February 22, 2015

WebSecurity in Asp.Net MVC 4 - Part 1

WebSecurity in Asp.Net MVC 4 - Part 1

In this blog, I’m explaining about the websecurity in asp.net mvc 4 and how to use it. In this blog, I will create a registration form to implement the websecurity.

Step 1:


First create an empty asp.net mvc 4 application. To use websecurity in your project , you have to install some packages :





Microsoft.AspNet.WebPages.Data -Version 2.0.20710





Microsoft.AspNet.WebPages.OAuth -Version 2.0.20710





Microsoft.AspNet.WebPages.WebData -Version 2.0.20710





Step 2:


Now create a database in SQL Server Management Studio and add a table named “UserProfile” like this:



Step 3:


Now add a controller to the project named “HomeController” and write the below code in it:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebSecurityMvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

    }
}



Step 4:


Now add a view to the project named “Index” and write the below code in it:


@{
    ViewBag.Title = "Index";
}
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<br />
<br />
<br />
<div class="row" style="width: 100%;">
    <div class="col-md-8 col-md-offset-2 well">
        <div class="col-md-2">
            @Html.ActionLink("Login", "Login", "Account")
        </div>
        <div class="col-md-2">
            @Html.ActionLink("Register", "Register", "Account")
        </div>
    </div>
</div>


Step 5:

Now add a model class named “Register” and write the below code in it:


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace WebSecurityMvcApp.Models
{
    public class Register
    {
        [Required]
        public string EmailId { get; set; }

        [Required]
        public string Password { get; set; }
       
        [Required]
        [Compare("Password", ErrorMessage = "Password and Confirm Password do not match")]
        public string ConfirmPassword { get; set; }

        [Required]
        public string Firstname { get; set; }

        [Required]
        public string Lastname { get; set; }
    }

}


Now add another controller to the project named “AccountController” and write the below code in it:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;
using WebSecurityMvcApp.Models;

namespace WebSecurityMvcApp.Controllers
{
    public class AccountController : Controller
    {

        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(Register model)
        {
            if (ModelState.IsValid)
            {
                if(!WebSecurity.UserExists(model.EmailId))
                {
                    WebSecurity.CreateUserAndAccount(model.EmailId, model.Password, new {
                        Firstname = model.Firstname,
                        Lastname = model.Lastname
                    });
                    TempData["Success"] = "Registration Successful";
                    ModelState.Clear();
                }
                else
                    TempData["Failure"] = "Email Id already in use.";
            }
           
            return View();
        }
    }
}


Step 6:


Now add another view named “Register” and write the blow code in it:


@model WebSecurityMvcApp.Models.Register

@{
    ViewBag.Title = "Register";
}
<link href="~/Content/toastr.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/toastr.min.js"></script>
<br />
@if (TempData["Success"] != null)
{
    <script> toastr.success("@TempData["Success"]")
    </script>
}

@if (TempData["Failure"] != null)
{
    <script> toastr.error("@TempData["Failure"]")
    </script>
}
<div class="row">
    <div class="col-md-8 col-md-offset-2 well">
        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary()
            <h2 class="text-center">Register</h2>
            <hr />
            <div class="row">
                <div class="col-md-12">
                    <div class="input-group">
                        <span class="input-group-addon">
                            <i class="glyphicon glyphicon-user"></i>
                        </span>
                        @Html.TextBoxFor(m => m.Firstname, new { @class = "form-control", @placeholder = "Fisrtname" })
                    </div>
                </div>
            </div>
            <div class="clearfix">&nbsp;</div>
            <div class="row">
                <div class="col-md-12">
                    <div class="input-group">
                        <span class="input-group-addon">
                            <i class="glyphicon glyphicon-user"></i>
                        </span>
                        @Html.TextBoxFor(m => m.Lastname, new { @class = "form-control", @placeholder = "Lastname" })
                    </div>
                </div>
            </div>
            <div class="clearfix">&nbsp;</div>
            <div class="row">
                <div class="col-md-12">
                    <div class="input-group">
                        <span class="input-group-addon">
                            <i class="glyphicon glyphicon-user"></i>
                        </span>
                        @Html.TextBoxFor(m => m.EmailId, new { @class = "form-control", @placeholder = "Email Id" })
                    </div>
                </div>
            </div>
            <div class="clearfix">&nbsp;</div>
            <div class="row">
                <div class="col-md-12">
                    <div class="input-group">
                        <span class="input-group-addon">
                            <i class="glyphicon glyphicon-lock"></i>
                        </span>
                        @Html.PasswordFor(m => m.Password, new { @class = "form-control", @placeholder = "Password" })
                    </div>
                </div>
            </div>
            <div class="clearfix">&nbsp;</div>
            <div class="row">
                <div class="col-md-12">
                    <div class="input-group">
                        <span class="input-group-addon">
                            <i class="glyphicon glyphicon-lock"></i>
                        </span>
                        @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control", @placeholder = "Confirm password" })
                    </div>
                </div>
            </div>
            <div class="clearfix">&nbsp;</div>
            <div class="row">
                <div class="col-md-12">
                    <input type="submit" value="Register" class="form-control btn btn-info" />
                </div>
            </div>
            <div class="clearfix">&nbsp;</div>
            <div class="clearfix">&nbsp;</div>
        }
    </div>
</div>


Step 7:


Now add connection string in the web.config file:


<connectionStrings>
    <add name="ConnectionString" providerName="System.Data.SqlClient" connectionString="Data Source=Data Source Name;Initial Catalog=Database Name;Integrated Security=true;" />
  </connectionStrings>


Step 8:


Now open Global.asax file write the blow code in it:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;

namespace WebSecurityMvcApp
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection("ConnectionString", "TableName", "Id", "EmailId", autoCreateTables: true);

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}



The above yellow line will initialize the database connection and will create the some tables in your database to implement the membership in your project.




Output

Now run the application:



You will see two links – Click on Register – this will open the register page:



If click the register button without filling up the values in the textboxes then:


Will show you the validation errors.


Now fill up the register form with correct values:



And click on the register button:



Will give you the confirmation message.


If you try to register with same email id then:





Will give you the error that email id is already in use.


In the next blog, I will implement the login form using websecurity in asp.net mvc 4.


1 comment:

  1. Online casino | kadangpintar
    Join the fun at KADangpintar, the world's leading online 메리트카지노 casino. Get started playing slots, blackjack, 온카지노 live 1xbet casino games and more.

    ReplyDelete