Web Security – Suraj | Coding Passion Tue, 09 Oct 2018 07:03:49 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.8 Validation & Security in MVC application /validation-security-in-mvc-application/ /validation-security-in-mvc-application/#respond Sun, 06 Sep 2015 16:32:15 +0000 /?p=407 Introduction

Validations in any application is so critical now a days that developers ought to be on their toes while developing any such critical and sensitive applications. Hackers are now in every corner of the society, avoid them restrict them to post non sense data into your applications. The attacks are so vulnerable that security guard of any application is mandatory.
security1
The security checks and implementations should be alert and active in the application to counter the attacks. Lets start learning about different types of validations we can have in our MVC application.

Server-Side Validation

Lets begin with simple server side validations. Server side validation are required when we post something to the server with an expectation for the response,usually while posting form data. The form data post is generally very vulnerable. The attacks are quite easier for the attacker here. Thus, we need to check on the server if we are receiving valid data or not on our end. Thus, server side validation can to some extent prevent nonsense input data. Lets discuss how to do validation explicitly using view model. Lets discuss how:
Explicitly means, we would be checking on server side after form post by the user, if the data input are valid input or not, then we post back the user with the validation message as response.
Suppose we have a model for the Registration of a user to an application. The model goesas below:

public class RegistrationViewModel(){
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string TelNo { get; set; }
}

Thus in the view/UI user will be displayed with the above labels and respective text boxes for input. The razor engine view page in the application looks like:

@model ServerSideValidationDemo.Models.RegistrationViewModel
@{
 ViewBag.Title = "Registration Page";
}

@using (Html.BeginForm())
{

    • @Html.LabelFor(m => m.FirstName) @Html.TextBoxFor(m => m.FirstName, new { maxlength = 50 }) @Html.ValidationMessageFor(m => m.FirstName)
  • @Html.LabelFor(m => m.LastName) @Html.PasswordFor(m => m.LastName, new { maxlength = 50 }) @Html.ValidationMessageFor(m => m.LastName)

 

  • @Html.LabelFor(m => m.Address1) @Html.PasswordFor(m => m.Address1, new { maxlength = 50}) @Html.ValidationMessageFor(m => m.Address1)

 

  • @Html.LabelFor(m => m.Address2) @Html.TextAreaFor(m => m.Address2, new { maxlength = 200 }) @Html.ValidationMessageFor(m => m.Address2)

 

  • @Html.LabelFor(m => m.TelNo) @Html.TextBoxFor(m => m.MobileNo, new { maxlength = 10 }) @Html.ValidationMessageFor(m => m.MobileNo)

 

 

}

Thus, the above snippet would bring the user the UI where the users would post their input and click submit. In the razor view page, you can see the HTML Helper ValidationMessageFor. This helper displays the Validation message returned after validation from the server as response, at the respective model property. Like for example, we want the user to enter the Model property First name as mandatory, then after validation the helper would display the validation message beside the First Name Text Box.
Now lets have a look at the Action snippet to which the post would call after Submit click.

[HttpPost]
public ActionResult UserRegistration(RegistrationViewModel registerModel){
     if (string.IsNullOrEmpty(registerModel.FirstName))
         {
             ModelState.AddModelError("FirstName", "Please enter your first name");
         }
     if (!string.IsNullOrEmpty(registerModel.TelNo))
         { 
             Regex telNoRegex= new Regex("^9\d{9}$");
             if (!telNoRegex.IsMatch(registerModel.TelNo))
             ModelState.AddModelError("TelNo", "Please enter correct format of Telephone Number");
         }
     if(ModelState.IsValid){
         return View("Sucess");  //Returns user to success page
         }
      else {
         return View();  //Returns user to the same page back again
        }
 }

Before explaining the above snippet, lets understand how this will be called after Submit click.
@using (Html.BeginForm()), this does the trick even without specifying the Action and controller. This actually internally calls the Post method of the current url, i.e. looks for the HttpPost attribute to the respective action name of the current url. Thus, in this way the post method of UserRegistration gets called and this also post the required view model to the action, fetching the values input by the user.
After the Action Result method gets called, there is check for the properties explicitly. Here, we check if the user has input into the First name or not. If the user skipd the First Name textbox and submits, then we post the user with the validation message saying “Please enter the first name”. This validation check will not let the user post the input, unless he adds the first name. Similarly, the telephone number is also validated with the regular expression(for the indian telephone number) given.
This was all about the validation being done explicitly.
Now, since we are developing an MVC application, it provides pre defined attributes which can be used to validate our post data. The attributes are called Data-Annotations attribute. Lets look at their usages below:
The use of data annotations can be extensively done in order to avoid heavying the controller post action,explicitly checking for each property. The data annotations attribute in a view model would look like below:

public class RegistrationViewModel(){
    [Required]
    [Display(Name = "First name")]
    [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    [Required(ErrorMessage = "Please Enter Telephone Number")]
    [Display(Name = "Tele Phone")]
    [RegularExpression(""^9\d{9}$"", ErrorMessage = "Please Enter Correct format of Telephone No.")]
    public string TelNo { get; set; }
}

The view model above uses Data Annotations attributes and all the required validations for the properties are provided. Lets discuss one by one:

    1. Required:- This attribute forces the user to enter the value for that specific property and then submit the form, else diplays “The FirstName is required.”. Mark here, the previous message would be a default error message where as for the Tele phone number, the custom error message would be displayed.
    2. Display(Name = ):- This attribute sets the label for the model property. We just need to specify
      @Html.LabelFor(m=>m.TeleNo). This would display the specified custom label for the property, here it would display Tele Phone
    3. RegularExpression:- This attribute is very handy specially when we have properties like Email Address, Tele Phone Numbers and specific expressions for passwords in the forms. We just specify the expression in the attribute and it validates the input from user and states if it is valid or else displays the error message.

Thus, here the view page would go like the same as above. And when we submit, the action post method called would be different i.e. much less code. Lets have a look at the action below:-

[HttpPost]
 public ActionResult UserRegistration(RegistrationViewModel registerModel){
    if (ModelState.IsValid)
      {
         return View("Success");//Return to the success 
      }
    else
      {
         return View();//Return back to the same view 
      }
 }

Thus, the data annotations here made it so simple and easy.
Here then comes another security vulnerability, i.e. Cross-Site Request Forgery Attacks, which can be easily attacked using the simple Fiddler. When we post any data, we can easily manipulate the data posted by one user using the fiddler and damp into the application and even ruin it. This is indeed very dangerous. Lets see how to prevent Cross site forgery attacks

Preventing Cross Site forgery Attacks

In MVC applications, while posting the form data, it is quite simple to prevent such request if understood properly. MVC provides the attribute [ValidatAntiForgeryToken] on the respective action. Lets see the flow in the snippet first.
First we need to place the AntiForgeryToken helper in the razor view page like:

@using(Html.Form("UserRegistration", "Register")) { 
    @Html.AntiForgeryToken() 
    //Then here normal rest form as mentioned above    
 }

Then in the controller “Register” for the action “UserRegistration”(POST) add the attribute like below:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UserRegistration(RegistrationViewModel registerModel){
   //ModeState Valid check and rest code goes here
}

Ok, so we have seen what two simple steps we need to do. Now lets understand how it does. What happens exactly when we do not place these attributes. How vulnerable our controller is and to what extent an attacker can affect the application. Suppose we are on an Edit page, where a user soughts to edit few of his login information. Now an attacker from over a third party domain and host a simple HTML that would post some information to the same Edit action, the user were to. Then, some how the user if navigates to the Html page set up by the attacker, the user unknowingly is posting unwanted data to the server and normal saving to the database. Here the attacker may be replacing the email ids or any other vulnerable information to his own and retrieving the user’s data. BOOM! This is crash, rather a crap!
Thus, what we need to do here, we need to check if the request to the server action is coming from the same domain, the user has logged in ! for this we need to have some header or property which will be mapped when a request is made and if matches then post else let the authentication fail.
This is actually what the attribute does. The ValidateAntiForgeryToken actually sets a cookie to the incoming reuest called __RequestVerificationToken, and the same __RequestVerificationToken is set for the domain in which the user is logged in. Thus, when a request is made from the same domain, the request header cookie should match and let the user post the data, but when a request is made from the third party domain, then the request is rejected since the __RequestVerificationToken will never match, just failing the authentication and preventing the Cross Site Forgery by any attacker.
Now here there is another problem. If any how the attacker gets to know the Anti Forgery Token, then what!! again crap! No there is a way out here as well. The attribute has ability to add a unique/different Salt every time so that the same token is not reused everywhere.

@Html.AntiForgeryToken("SALT") //The salt can be any sort of string(homogeneous mixture :))

[ValidateAntiForgeryToken("SALT")]

Another concept that is vulnerable to such attacks and may breach the security in the application is SQL Injection Lets discuss this in brief. 🙂

SQL Injection Attacks & Prevention Techniques

What exactly is SQL Injection attack? thinkzoo
SQL Injection is an attack to fool and manipulate the application database. This is done through the malicious input from the user during post methods and if the posted data is not validated before being executed as sql query. This is really very dangerous which can let attackers get all the sensitive data or even delete the records from all tables, truncating them, just by posting a simple query to drop instead of actual data.
In this, the objective of the attacker is to post their query into the application and let the server run and give him the response if not handled in the server end. Lets see how:
Suppose we have a sql query to select the names of houses and display. The query would be like:

var sqlTobeExecuted = "SELECT HouseID, HouseName"+
    "FROM House " +
    "WHERE Address LIKE '" + searchInputParam +"%';
SqlDataAdapter da = new SqlDataAdapter(sqlTobeExecuted , DbCommand);

The above query is not parameterized and is a simple query in string format to get the house details. Now suppose the attacker posts the searchInputParam (which originally comes from the textbox input of the user) as

‘ UNION SELECT id,name FROM sysobjects;–

Mark the statement what becomes after that is passed to the string query,

SELECT HouseID,HouseName FROM House
WHERE Address LIKE ” UNION SELECT id,name FROM sysobjects;–%’

The first apostrophe in the searchInputParam closes the Like parameter in the SQL query and the double dashes “–” comment out the rest of the query. Thus that gives the list of all the HouseNames and also all the tables present in the database . Even they can also get the ids of the sysObjects and use the Ids to retrieve the column names of the database table they want. Suppose there is a table named Users. Oviously the table would have all the user details. Thus, with the id and the table name the attacker can retrieve the column names of the Users table using the below query:

‘ UNION SELECT name FROM syscolumns WHERE id = “USERID”;–

Thus,the whole of the database can be exposed to malicious users at a single click.
To prevent this,

      • Encrypt the essential and sensitive data like password, credit card info and other details. So that to some extent if by any how they get the details they cannot decrypt it. Use one way hashing to encrypt the record data.
      • Using parameterized queries instead of strings, in order to avoid directly injecting the values from the User input to the query as we saw in the above section. A parameterized query would prevent the malicious input and it would look like below:
        var commandToBeExecuted = "SELECT HouseID, HouseName FROM House"+
            "WHERE Address  Like @Address";
        SqlCommand cmd = new SqlCommand(commandToBeExecuted , conn);
        cmd.Parameters.Add("@Address",address);

        As we see in the above query we avoid passing directly the string input, instead we are using parameters into the SQL query, which would prevent such attacks.
      • use of parameterized Stored Procedures, which also prevent and prove to be a good solution to these mallicious attacks of injection. Also it is advisable to not trust them completely/blindly so it is always better to check for the sensitive data from user inputs and then execute the Stored procedure. This can be done, where the developer can think there are chances of vulnerability.
      • Entity Framework & LINQ, it is interesting to note here is while using LINQ to entity, the query generation does not use the string based approach, rather it uses the object model API, thus being not susceptible to SQL injection attacks.

Authentication & Authorization

These two are very very very…important in any application and these are two different concepts all together but are used to solve the same thing,i.e. Security. When we develop an secure application, the Login is highly essential. Thus, properly authenticating users to the application & authorizing users to particular section of the application is challenging. Usually Forms Authentication is implemented across MVC applications. In the web.config file, the following configuration is set:

Only this will not set the authentication. You need more set up be done. This would involve a lot of configuration. WebSecurity in MVC makes it easy and secure to be implemented. It provides tables and hashing as well. The hashing it provides is one way and very secure. You can learn more about implementing Web Security in MVC from
Web Security In MVC
Thus after setting this authentication, then the important thing is Authorization, which can be provided on controller level, action level, which can be customized in order to check for the access levels along with the sessions. Only Authorize attribute would let the check for the session, we can customized to check for the roles and access levels for the screens as well.

[Authorize]
 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }

In the above snippet, the entire controller has been authorized. That is each method inside the controller will be first authorized.

public class HomeController : Controller
    {
      public ActionResult Index()
        {
            return View();
        }
       [Authorize]
       public ActionResult GetHome(){
         return View()
       }
    }

Here, only the action method GetHome is authorized, not the whole controller.
Thus, Authentication and Authorization are very important factors that ought to be taken into consideration.

More security considerations in MVC

Straight from the OWASP scurity points,
Its advisable to hide the MVC versions as well as Asp.Net versions we use, never expose the versions through the headers.

X-AspNet-Version 4.0.30319
X-AspNetMvc-Version 5.0

We need to hide the versions which appears in the Network tab of the developer table.
Lets know how to remove the versions of Asp.Net and Asp.Net Mvc from the headers.

    • Asp.net Version:-To hide the X version of the Asp.Net we use the below Web.Config change.

      The above will hide the Asp.net versions.
    • Asp.Net MVC Versions:- To hide the X version of the Asp.Net MVC we use the below change in the Application_Start method of the Global.asax. The snippet would go like below:-
      protected void Application_Start()
              {
                  MvcHandler.DisableMvcResponseHeader = true;

      This hides the Asp.Net MVC version from the headers in the Network tab.
    • Lastly, there are chances of exposing the Users to the Yellow screen of death, when an exception occurs in the application and is unhandled. Thus, it is advisable to have a custom error page, where users will be landing when exception occur. Lets see how:
      Custom errors in the Web config needs to be on. There are three modes of the Custom errors. They are:

      1. On:-
        –Prevents the stack trace that is shown when exceptions arise
        –Also allows to display custom error pages to the end user
        –Custom error pages shown to both Remote Clients as well as Local
      2. Off:-
        –Makes the end user view the description of the exception along with the entire stack trace.
        –ASP.NET error/exception and stack trace shown to both Remote clients and Local as well.
      3. Remote only:-
        –This is the best among all for the developers’ perspective, as this allows the Remote clients to view thecustom error messages/pages.
        –Allows the Local users/especially developers to view the ASP.NET errors.
        –This is the default value.

      The other attribute which is used to the custom error element is defaultredirect. This is used to redirect the users to a default page when exceptions occur.

      The exceptions can also be handled globally , application level by using the below snippet:

      protected void Application_Error(Object sender, EventArgs e)
      {
          Exception ex = Server.GetLastError();  //self explanatory gets the most recent error
          Server.ClearError();  //self explanatory clears the error 
              //(Required to clear as otherwise user gets to see the default ASP.NET error handlers)
          Response.Redirect(""); //default redirect. 
      }

      For details you can follow: Custom Errors

      Conclusion

      Thus, security and validations are very important features to be implemented in any application now a days. According to forbes in a day 30,000 sites were hacked. This is truly an astonishing numbers. And in today’s world most of the sensitive information are being stored on cloud. Thus, in any application the data have a great chance of being exposed and hacked. So security is a major concern and needs to be handled very carefully.
      Hopefully, Some of the major points are discussed above and can be implemented in any application to avoid any sort of breaching.

      References

      How can I miss the references from which I learnt and got this opportunity to share with the world.
      OWASP Cheat Sheet
      Security testing
      Sql Injection and Entity Framework

]]>
/validation-security-in-mvc-application/feed/ 0
WebSecurity in MVC /websecurity-in-mvc/ /websecurity-in-mvc/#respond Mon, 02 Mar 2015 19:26:10 +0000 /?p=279 Introduction

In this article , I would be discussing a very interesting topic called WebSecurity in MVC applicationa and how easy and simple it is to implement and understand. Let me share a small incident for which I came across this concept. Usually we create an MVC application and select a template may it be Internet or Empty (these two are used frequently). Based on these templates, the web project gets scaffolded and we get the final project structure to work on. If we select an Internet application, then by default scaffolding we get controller “Home” and “Account” created. ASP.NET MVC bydefault provides the authentication through the Web Security. I tried to customize the way authentication was done and then realized this is so simple and easy, as it reduces so many lines of our codes. Lets discuss more on this with a small Demo.

Lets Play..zoo

Lets briefly get to know what Web Security is!! According to MSDN, it provides security and authentication to Asp.Net web applications with many more features like user account creation, Login User and Log off, Reset & Change Password, with the help of its in-built functions. It internally also does the Password hashing which is one of the main concern during creation of a user account. The different properties and methods are well explained in the MSDN link given above. This is usually called as Helper class that is present in the namespace- “System.WebMatrix.WebData”. When an Internet template is chosen we would find the “Dynamic Link Library” , WebMatrix.WebData.dll
Lets create a new project in Visual studio:
Here I create a new Asp.Net Web Project and name it as “WebSecurityDemo” and after clicking on ok the final creation of project in Visual Studio looks like below:
Capture1
As we can see in the above image, the project is scaffolded based on the Internet template in MVC. This by default creates the Home controller and Account controller with all kinds of authentication and security. This default web application without any coding, gives user options to Register, Login, Log off and OWIN authentication using Facebook, Twitter, G+(this requires some modification which I will be discussing later). But how does this happen!! This is done by the Authorize attribute provided by MVC, which is one of the best assets of MVC. Just specifying an attribute like “[Authorize]” which restrict user access to the methods/actions if specified at controller level or also can be specified at action level, just like the below snippet:

[Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {
          [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

In the above snippet as you can see the Authorize attribute is given at the controller level, which will restrict users to access the action methods defined inside this controller,but as you can also see another attriute called [AllowAnonymous] this is provided on the action method, which means any user can access this action using the url directly. This attriute overrides the controller level attribute here. The best part to this authorize attributeis we can also override this and create our own custom Authorize attribute like below:-

namespace WebSecurityDemoTest.Filters
{
    public class WebSecurityAuthorize:AuthorizeAttribute
    {
        protected bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!httpContext.Request.IsAuthenticated)
            {
                return false;
            }
            if (HttpContext.Current.Session["SessionHelper"] == null)
            {
                return false;
            }

            return true;
        }

        protected void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectResult("/");
            base.HandleUnauthorizedRequest(filterContext);
        }

    }
}

As you might see here, I have created a custom authorize attribute, which first checks if the current http Request is Authenticated or not, Since we will be using FormsAuthentication, this IsAuthenticated gets initialized after Login or inside the LoginPost method like:

FormsAuthentication.SetAuthCookie(userName,true);

The boolean value true does the trick. After successful login when the AuthCookie is set, the IsAuthenticated for the request is set to true. Now if that is not true, then it is handled by the other method i.e. HandleUnAuthorizedRequest. When there is an unauthorize request it checks and return the user back to the default page i.e. the login page. Here, as you can also see I have checked for the session also, after the user has a successful login, I create a session and store the values as is usually done, and based on that also I check if the session is not null, if the AuthorizeCore method returns true, then the user navigates to the desired landing page.  Thus, this is how a custom authorize attribute is created.

Now lets discuss more about another class that is created inside the Filters folder, when the project gets created i.e. <em>”InitializeSimpleMembershipAttribute.cs”</em>. This class is responsible to initialize the tables required by the Web Security to run in the database. Lets see how the class looks like and discuss about that:-

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Threading;
using System.Web.Mvc;
using WebMatrix.WebData;
using WebSecurityDemoTest.Models;

namespace WebSecurityDemoTest.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
    {
        private static SimpleMembershipInitializer _initializer;
        private static object _initializerLock = new object();
        private static bool _isInitialized;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Ensure ASP.NET Simple Membership is initialized only once per app start
            LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
        }

        private class SimpleMembershipInitializer
        {
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see https://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        }
    }
}

As you can see, since this class extends itself from the ActionFilterAttribute, then it is used as an attribute only, usually at the controller level as you can check in the first code snippet. [InitializeSimpleMembershipAttribute]. This attribute, what it does in simple language is ensures before any action runs, that the membership has been created at the database level or not. So that when a userregisters it stores the data in the system defined tables. System Defined Tables!!thinkzoo. Yes the tables required for the Websecurity are created once we build and run the application and the controller action gets called which has the attribute defined. But how? The below peice of code snippet does the trick:-

WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

As you can see the method “InitializeDatabaseConnection” present in the WebSecurity class, explains itself what it does. This initializes the database connection based on the first parameter which is the database name here. Then the sql table with the name gets created, with columns UserId as the primary key and the UserName associated with the user who registers. Now we need to add a Database context to our project:

  1. Right click on the Model folder. Select Add new Item:capture2
  2. Then select Data and Add an Ado.Net Entity Data Model with a valid name.Capture3  I have named the data model as WebSecurity.edmx. This creates the conceptual model for the database after we give the connection.
  3. Then we need to specify the connection to the database. You can create a sample database or use an existing one. I will be using one existing one and will show how the tables for websecurity get generated. Select Generate from databaseCapture4
  4. Then the connection needs to be setup. Choose your local server, so in the database textbox enter “.(dot)” which means local DB and that would list the databases present in your local. Choose anyone you wish to.                                                Capture5                  Capture6
  5. Thus, when the connection is success and is established, we can find the connection string in theWeb.Config file.Capture7
  6. Then since you can scroll up and see in the InitializeSimpleMembership.cs we have the DefaultConnection specified, we need to change the configuration specified defaultin the web.config connection string, that is change the Data Source = . and remove the AttachedDbFileName entirely and then specify the Initial Catalog as the database name which you have added during the db connection. Finally the connection string with name “DefaultConnection” looks like:
    <add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=Customer;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

     
  7. Thus, we have reached the end to the set up. Now clean and build the solution once and then run. When we run the application, we land on the Home page as the Home controller has no authorization. And also remember one thing the membership/ websecurity tables will only get created once the InitializeSimpleMembership attribute is hit and in the above snippets it gets hit only when the Account controller is accessed. So when we go to any action method that is AllowAnonymous as we also need to land on the page, So we click on the Register.Capture9
  8. The below image shows the table created once the attribute is hit/executed. “dbo.webpages_Membership” stores all the information related to the User registered with the User password that is hashed and that to one way for more security. User Id which acts as the foriegn key here to the UserId primary key in the UserProfile table which also contains the UserName which is asked during the registration.Capture10
  9. After the registration, you will find yourself logged in as the UserName entered and the data in the tables would look like: Capture11Capture12Capture13
  10. Thus this is how the simple attribute, internally does everything.

Now lets check for the codes , the method WebSecurity class implements. First is the “WebSecurity.UserLogin”

WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe)

This method, takes the UserName, the password and the persistCookie which is the Remember Me check box. This maps the webpages_Membership table and the UserProfile table for the combination of the userName and password, if this satisfies or is perfectly mapped, it redirects user tothe authenticated page, else throws him back to the Login page. if wrong password is entered then it gives the ModelState error as incorrect username and password. If the Remember Me is checked, then the IsPersistent is true in the cookie which is created, then when next time even after closing the browser we come, the cookie persists based on the span it has and authenticates the user without the credentials.

The next method used is “WebSecurity.ChangePassword”

WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)

This method takes the unique username, with the old Password and also the new Password as the parameters. It internally matches first the old password with the User name (Logged In) and then if satisfies stores or replaces the old password with the new one encrypting it or hashing it. This is that simple. 🙂

Now the other method and an important one, when the user registered, how did the data get saved into the table!! Nice question .. 🙂 The answer is another inbuilt method that does the trick here i.e. “WebSecurity.CreateUserAndAccount”

WebSecurity.CreateUserAndAccount(model.UserName, model.Password)

what this does is, takes the parameter as the unique user name and the password, then adds the user name into the UserProfile table that returns the UserId and whichinturn is used as the foreign key with one to one relationship and hashes the password and stores in the webpages_Membership table. This is how a user gets registered so simply using WebSecurity.

There is also a method called Logout, which simply logs out a user. “WebSecurity.Logout()”.

Conclusion

Thus, I discussed in this article the details of WebSecurity class and how to use that in the MVC application. The method and the membership authentication is the same, just we need to customize inorder to have our own hold over it. It is very easy ans simple to use, which makes the code less redundant and reusable and mainly maintainable. This follows usually the DRY concept which is Don’t Repeat Yourself. Thus this suggests to use evrything once, like have an Authorize attribute may it be Custom and reuse it wherever required. WebSecurity has everything defined, we just need to explore and use its methods and properties extensively to reduce the level of coding and LOC.
Thus here I end my article I hope I could explain atleast something.
Though I am not an expert and moreover a human, so mistakes are ovious. i would be glad if you find any or also suggestions and discussion are most welcome.
Share and learn.
CP

]]>
/websecurity-in-mvc/feed/ 0