Skip to main content

ASP.NET custom forms authentication part 2

Did not receive any comment for Part 1 but going by the stats I think it has been useful for few of you. Thus I think I should Part 2.


In this article we are going to demonstrates how to set up custom forms authentication.  The login page assumes logging in using username and password (as demonstrated in Part 1).  The user roles for the site are stored in the database. For user identification I need userID and for authorization I need to know which group does user belong to. Wait a minute, ASP.NET provides way to handle it in web.config.


like this:  


 <location path="Admin">
    <system.web>
      <authorization>
        <allow roles="Admin"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>           


But we are not using Membership Provider so how ASP.NET will come to know about it. There are two ways we can achieve this. One is to write a custom Membership Provider and Second is to update the principal which we are going to see.


We will create a user identity class.This class will implement IIdentity interface.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;


namespace TechBook.Presentation.LoginClasses
{
    public class UserIdentity: IIdentity
    {
        private bool isAuthenticated;
        private string authenticationType;
        private string userID;
        private string firstName;
        private string lastName;
        private List roles;
                
        public UserIdentity(string UserID, bool IsAuthenticated, string AuthenticationType)
        {
            userID = UserID;
            isAuthenticated = IsAuthenticated;
            authenticationType = AuthenticationType;
        }


        public bool IsAuthenticated
        {
            get { return isAuthenticated; }
        }
        public string AuthenticationType
        {
            get { return authenticationType; }
        }


        public string Name
        {
            get { return userID; }
        }


        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }


        public string LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }


        public List Roles
        {
            get { return roles; }
            set { roles = value; }
        }
    }
}



We will create a custom principal class. The class will implement IPrincipal interface.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;


namespace TechBook.Presentation.LoginClasses
{
    public class UserPrincipal :IPrincipal
    {
        private UserIdentity _userIdentity;


        public UserPrincipal(UserIdentity userIdentity)
        {
            _userIdentity = userIdentity;
        }


        public System.Security.Principal.IIdentity Identity
        {
            get { return _userIdentity; }
        }


        public bool IsInRole(string role)
        {
            return _userIdentity.Roles.Contains(role);
        }
    }
}

We have created these classes as we know identity and role are must to implement authentication and authorization.  Application must be able to identify the user.

Now we need to write code for user authentication. 

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

namespace TechBook.Presentation.LoginClasses
{
    public class SecurityManager
    {
        public bool Authenticate(string userName, string password)
        {
            BusinessEngine.Users user = new BusinessEngine.Users();

            user.UserName = userName;
            user.Password = password;

            if (new Business.Controller.UserController().validateUser(user) == 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public UserPrincipal ConstructUserPrincipal(System.Security.Principal.IIdentity iidentity)
        {
            int userId = Convert.ToInt32(iidentity.Name);

            if (userId &gt; 0)
            {
                BusinessEngine.Users user = new BusinessEngine.Users();
                user = new Business.Controller.UserController().getUserById(userId);

                UserIdentity uidentity = new UserIdentity(userId.ToString(), iidentity.IsAuthenticated, iidentity.AuthenticationType);
                uidentity.FirstName = user.FirstName;
                uidentity.LastName = user.LastName;

                List role = new List();
                if (user.UserType.ToString().ToUpper().Equals("A"))
                {
                    role.Add("Admin");
                    uidentity.Roles = role;
                }

                UserPrincipal uprincipal = new UserPrincipal(uidentity);

                return uprincipal;
            }
            else
            {
                return null;
            }
        }
    }
}

We have kept the userId in Context.User.Identity.Name (see UserIdentity class). using this we can query the database and get the user information. 

Login Code


protected void btnLogin_Click(object sender, EventArgs e)
        {
            TechBook.Presentation.LoginClasses.SecurityManager obj = new                    TechBook.Presentation.LoginClasses.SecurityManager();
            if (obj.Authenticate(txtUserName.Text.Trim(), txtPassword.Text.Trim()))
            {
                BusinessEngine.Users user = new BusinessEngine.Users();
                user.UserName = txtUserName.Text.Trim();
                user.Password = txtPassword.Text.Trim();
                
                user = new Business.Controller.UserController().getUser(user);
                FormsAuthentication.RedirectFromLoginPage(user.UserId.ToString(), false);
            }
        }

We need user and role information everytime a request is received and thus we need to bind the code with authentication module. 

Global.asax code


protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            if (this.User != null)
            {
                TechBook.Presentation.LoginClasses.SecurityManager obj = new TechBook.Presentation.LoginClasses.SecurityManager();

                TechBook.Presentation.LoginClasses.UserPrincipal principal = obj.ConstructUserPrincipal(this.User.Identity);

                this.Context.User = principal;

            }
        }

Hope this will help someone.

Comments

  1. Hi,

    Very nice blog.

    Can you please send working code of this to my email?

    Thanks.
    Sujal

    ReplyDelete
  2. Hi Sujal, Thanks for your nice words. The code present in the article is working sample only. If you still have any doubts do let me know I will send you a sample project.

    Cheers :)

    ReplyDelete
  3. Hi mate,
    what is BusinessEngine.Users

    I can't find where is it declared or where it is coming from?

    Regards

    ReplyDelete
  4. BusinessEngine.Users is a class which provides you user information. You can create your custom class for this. It has nothing to do with the framework as a whole

    ReplyDelete

Post a Comment

Popular posts from this blog

Laravel XAMPP MySQL artisan migrate install error mysql.sock

In my previous post I wrote about setting up Laravel 4 on Mac with XAMPP . When I tried to use migrations (using artisan) I faced some issue. I will also post about Laravel migrations soon.    php artisan migrate:install Error :                                                     [PDOException]                                       SQLSTATE[HY000] [2002] No such file or directory                                              Solution : We need to tell artisan which mysql we want it to use. For this to work we need to porivde it with mysql.sock which we want it to use. So change your database settings like this: 'mysql' => array( 'driver'    => 'mysql', 'host'      => 'localhost',     'unix_socket' => '/Applications/xampp/xamppfiles/var/mysql/mysql.sock', 'database'  => 'wedding', 'username'  => 'root', 'password'  => '', '

Add (Drop) a new article (table) at publisher in merge replication

Let us add the article using the GUI first. First of all create the table on publisher database. Now right click on the publisher and select properties from the menu. Click on articles. Uncheck the - "Show only checked articles in the list" checkbox, in order to see the newly added table. Select the table as shown in the figure below. Press ok The article has now been added to the publisher We now need to recreate the snapshot Right click the publication and select – “View snapshot agent status”. Click start to regenerate snapshot. Now right click on the subscription (I have both on same server you may have on different servers) and select “View synchronization status” Click on start on the agent. The schema changes will propagate to the client if you have "Replicate schema changes" property set to true in the publisher.

Check SQL Server Job status (State) using sp_help_job and xp_sqlagent_enum_jobs

This article is about checking the status of a SQL job. In our work place we have lot of SQL jobs. These jobs will run whole day and are business critical. They will load the data and generate extracts which will be used by business people. Thus, it becomes quite essential to support the system efficiently so that the job finishes in time and as desired. Also, while designing a new system sometimes we need to check the dependency of one job over another. In such scenario we need to check whether a particular job has finished or not. All this can be achieved in SQL Server by using the procedures:- sp_help_job xp_sqlagent_enum_jobs Note: xp_sqlagent_enum_jobs is an undocumented proc inside of sp_help_job and is used extensively to get SQL agent job information. sp_help_job: This procedure gives some insight into the status, and information, about a job. This stored procedure provides information such as last start time, job status etc. Syntax sp_help_job { [ @job_id= ] jo