asp.net mvc authorization roles

Custom Roles Base Authorization in ASP.NET MVC

Hello everyone, I am going to share the code sample to roles base authorization and authentication in ASP.Net MVC 5 using FilterAttribute and AspNetUserRoles.

The Steps detail as given below.

ASP.NET Forms Authentication

namespace Authorize.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        [HttpPost]
        [AllowAnonymous]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                     int timeout = 525600; // Timeout in minutes, 525600 = 365 days.
                     string UserData = GetUserData(model);
                     //// Create and tuck away the cookie
                     FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddDays(30), rememberMe, UserData, FormsAuthentication.FormsCookiePath);

                    //To encrypt FormsAuthenticationTicket ticket set the protection attribute of the forms element to All or Encryption.
                    string encTicket = FormsAuthentication.Encrypt(authTicket);

                    HttpCookie AuthCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                    System.Web.HttpContext.Current.Response.Cookies.Add(AuthCookie);
                }
           }
        }
    }
}

Authorize controller by Roles

namespace Authorize.Controllers
{
    [CustomAuthorize(Roles = "Client")]
    public class UsageController : BaseController
    {

        /// <summary>
        /// This method is used to render dashboard view.
        /// </summary>
        public ActionResult Index()
        {
            return View();
        }
   }
}

CustomAuthorizeAttribute class using AuthorizeAttribute

namespace Authorize.Security
{
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            AspDotNetUserRepository _aspNetRepo = new AspDotNetUserRepository();
            if (filterContext.HttpContext.Request.IsAuthenticated)
            {              
                var authorizedRoles = ConfigurationManager.AppSettings.Get("admin");
                Roles = String.IsNullOrEmpty(Roles) ? authorizedRoles : Roles;
             
                AspNetUser user = _aspNetRepo.GetAspNetUser(Convert.ToString(HttpContext.Current.User.Identity.Name));
                if (user != null)
                {
                    string userRole = _aspNetRepo.GetUserRole(Convert.ToString(user.Id));
                    if (!String.IsNullOrEmpty(userRole))
                    {
                        if (!userRole.Equals(Roles))
                        {
                            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "Controller", "Error" }, { "Action", "AccessDenied" } });   
                            FormsAuthentication.SignOut();
                            base.OnAuthorization(filterContext);//returns to AccessDenied page URL.     
                        }
                    }
                }
            }
        }
    }
}

App Settings for Roles

  <appSettings>
    <!-- For Authrization role -->
    <add key="admin" value="adminUser"/>
  </appSettings>



ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book