Part 4 - How to implement custom Forms Authentication in ASP.NET MVC4 application

In this post, I am going to implement custom user principal and identity in ASP.NET MVC4 application.
The IPrincipal and IIdentity are important to authentication and authorization process in .NET. The IPrincipal tells us if the user is authenticated or in a given role and The IIdentity holds information about the user (we can access with "HttpContext.Current.User" Property) . But in the default IIdentity we have only limited information (AuthenticationType, IsAuthenticated and Name) about the user. So, I would like to implement them myself, because it allows me to pass a bit more useful data around in the cookie.

I have split the entire application split into following parts for making things more simple and understandable.

Index
Welcome Guest - This is for all the anonymous user
Part 4 - How to implement custom Forms Authentication in ASP.NET MVC4 application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;

namespace MvcAuthentication
{
    public class MyIdentity : IIdentity
    {
        public IIdentity Identity { get; set; }
        public User User { get; set; }

        public MyIdentity(User user)
        {
            Identity = new GenericIdentity(user.Username);
            User = user;
        }

        public string AuthenticationType
        {
            get { return Identity.AuthenticationType; }
        }

        public bool IsAuthenticated
        {
            get { return Identity.IsAuthenticated; }
        }

        public string Name
        {
            get { return Identity.Name; }
        }
    }
}

Posted By :