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

Create a background / taskbar application in c# .NET

Recently, I was working on integration of two windows applications. First application will launch the second application on login and then they both will communicate using pre-defined set of instructions. There were some complications (I am not going into them) and thus we decided to have a third application which actually will act as mediator. First application will launch the mediator (third application) and it will launch the second application. For this purpose we needed to create a task bar application (which will run in background). How To ·          Create a new windows project and delete the default form (Form1). ·          In Program.cs create a new class and inherit it from Form. ·          Please refer the code below. ·          Now change the Main method. In Application.Run change the startup objec...

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...

Java 8 JMX Default Metrics

This is more of a note. Here you can find default types and attributes for JMX on top of Java 8. Code: I will clean and explain it later :( private static void WriteAttributes(final MBeanServer mBeanServer, final ObjectName http) throws InstanceNotFoundException, IntrospectionException, ReflectionException { MBeanInfo info = mBeanServer.getMBeanInfo(http); MBeanAttributeInfo[] attrInfo = info.getAttributes(); System.out.println("Attributes for object: " + http +":\n"); for (MBeanAttributeInfo attr : attrInfo) { System.out.println(" " + attr.getName() + "\n"); } } Attributes for object: java.lang:type=MemoryPool,name=Metaspace:   Name   Type   Valid   Usage   PeakUsage   MemoryManagerNames   UsageThreshold   UsageThresholdExceeded   UsageThresholdCount   UsageThresholdSupported   CollectionUsageThreshold   Collectio...