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

In this post, I am going to implement custom Role Provider in Forms authentication in ASP.NET MVC4 application.

There might be multiple types of users (Like Administrator, registered users, Agent users) in an application, who can perform different type of action based on the roles assigned to a user. For this authorization process ASP.NET offers a RoleProvider class. 

The class includes method to create and delete roles, to add and remove users in a role, and tell whether a user belongs to a particular role.

Here we will implement our custom role provider that will be used to return the roles that a user has to take full control of the database and authorization process mechanism.


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 3 - How to implement custom Forms Authentication in ASP.NET MVC4 application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.Security;

namespace MvcAuthentication
{
    public class MyRoleProvider : RoleProvider
    {
        private int _cacheTimeoutInMinute = 20;
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override void CreateRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            throw new NotImplementedException();
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();
        }

        public override string[] GetAllRoles()
        {
            throw new NotImplementedException();
        }

        public override string[] GetRolesForUser(string username)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                return null;
            }

            //check cache
            var cacheKey = string.Format("{0}_role", username);
            if (HttpRuntime.Cache[cacheKey] != null)
            {
                return (string[])HttpRuntime.Cache[cacheKey];
            }
            string[] roles = new string[]{};
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                roles = (from a in dc.Roles
                             join b in dc.UserRoles on a.RoleID equals b.RoleID
                             join c in dc.Users on b.UserID equals c.UserID
                             where c.Username.Equals(username)
                             select a.ROleName).ToArray<string>();
                if (roles.Count() > 0)
                {
                    HttpRuntime.Cache.Insert(cacheKey, roles, null, DateTime.Now.AddMinutes(_cacheTimeoutInMinute), Cache.NoSlidingExpiration);

                }
            }
            return roles;
        }

        public override string[] GetUsersInRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            var userRoles = GetRolesForUser(username);
            return userRoles.Contains(roleName);
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            throw new NotImplementedException();
        }
    }
}
Posted By :