Custom user authorization based with roles in asp.net mvc

GotaloveCode

I have created a custom authentication and authorisation for my users.The problem I am facing is how to get mvc to check that role from inside my users table matches the [Authorize(Role)] on my controller so as to set httpauthorised to true.Below is my customauthorise class.

 [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class CustomAuthorizeAttribute : AuthorizeAttribute 
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Controller.TempData["ErrorDetails"] = "You must be logged in to access this page";
            filterContext.Result = new RedirectResult("~/User/Login");
            return;
        }

        if (filterContext.HttpContext.Request.IsAuthenticated)
        {
            using (var db = new GManagerDBEntities())
            {
                var authorizedRoles = (from u in db.Users
                                       where u.Username == filterContext.HttpContext.User.Identity.Name
                                       select u.Role).FirstOrDefault();
                Roles = String.IsNullOrEmpty(Roles) ? authorizedRoles.ToString() : Roles;
            }
        }

        if (filterContext.Result is HttpUnauthorizedResult)
        {
            filterContext.Controller.TempData["ErrorDetails"] = "You do nat have necessary rights to access this page";
            filterContext.Result = new RedirectResult("~/User/Login");
            return;
        }

    }
    public CustomAuthorizeAttribute(params object[] roles)
    {
        if (roles.Any(r => r.GetType().BaseType != typeof(Enum)))
            throw new ArgumentException("roles");

        this.Roles = string.Join(",", roles.Select(r => Enum.GetName(r.GetType(), r)));
    }
}

below is my controller with decoration

 [CustomAuthorize(Role.Administrator)]
    [HttpGet]
    public ActionResult CreateEmployees()
    {
        return View();
    }

and my enum for role

public enum Role
{
    Administrator = 1,
    UserWithPrivileges = 2,
    User = 3,
}

and model

public class UserModel
{
    public int UserID { get; set; }
    [Required]
    [Display(Name="Username:")]
    public string Username { get; set; }
    [Required]
    public string Password { get; set; }
    public int Role { get; set; }
}

see pastie for clear view pastie

links I have viewed in trying to solve this among others but I cant seem to piece it togetherMVC 3 Authorize custom roles http://forums.asp.net/p/1573254/3948388.aspx

Customized authorization attribute in MVC 4 with Roles

GotaloveCode

using the link shared by @VikasRana http://www.codeproject.com/Articles/578374/AplusBeginner-splusTutorialplusonplusCustomplusF

I got rid of my enum Role and my method

public CustomAuthorizeAttribute(params object[] roles)
    { ...}

I then changed Role in my model to be a string e.g. User.Role="Admin" instead of int. In my onAuthorization method I changed it to:

` public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Controller.TempData["ErrorDetails"] = "You must be logged in to access this page";
            filterContext.Result = new RedirectResult("~/User/Login");
            return;
        }
        if (filterContext.Result is HttpUnauthorizedResult)
        {
            filterContext.Controller.TempData["ErrorDetails"] = "You don't have access rights to this page";
            filterContext.Result = new RedirectResult("~/User/Login");
            return;
        }
        }

and in my global.asax added this.

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
    {
        if (FormsAuthentication.CookiesSupported == true && Request.IsAuthenticated== true)
        {
            if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                try
                {
                    //let us take out the username now                
                    string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                    string roles = string.Empty;

                    using (GManagerDBEntities db = new GManagerDBEntities())
                    {
                        User user = db.Users.SingleOrDefault(u => u.Username == username);

                        roles = user.Role;
                    }
                    //let us extract the roles from our own custom cookie
                    //Let us set the Pricipal with our user specific details
                    HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
                      new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
                }
                catch (Exception)
                {
                    //something went wrong
                }
            }
        }
    }   

Above method is not ideal though.It gets run for every simple page request about 3 times or more.

So here is solution 2:better solution Implement a custom role provider since we are already using custom role implementation.Simply follow this linkhttp://techbrij.com/custom-roleprovider-authorization-asp-net-mvc

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Individual page authorization based on roles in ASP.NET MVC 5

Asp.net Core MVC Roles and Authorization

Asp Net Core 3.1 Authorization by Custom Roles

Custom Authentication and Authorization for different user types in asp.net mvc

How to create custom Authorization for ASP.NET MVC5 Web Api With Roles and Permitions for them?

ASP.Net MVC List of User and their Roles

Custom authorization in ASP.NET Core with enum roles

custom authorization in asp.net core mvc

Adding custom roles to windows roles in ASP.NET MVC 5

LinqToTwitter user authorization ASP.NET MVC

Claims based authorization with ASP.NET MVC

ASP.NET Core Custom Role Based Authorization (Custom User.IsInRole)?

ASP.NET Core 3.1 MVC Access Denied role based authorization - Conflict with custom UserClaimsPrincipalFactory

Creating my custom security role and custom user group tables, to implement custom authorization for my asp.net mvc web application

Custom Role Provider with ASP.net MVC -- Changing Roles

ASP.NET MVC Authorize user with many roles

Asp Core MVC 2.1 Authorization based on policies per user?

ASP.Net MVC Authentication - Hide Element in View based on roles

Asp.net MVC Access Custom Error Page Without Authorization

ASP.Net MVC Custom Authorization Policy Provider in razor view

Dynamic authorization of roles asp.net core

Asp.NET Core MVC Role based Authorization

ASP.NET Core Custom Policy Based Authorization - unclear

.NET Core 2.1 MVC Identity Authorization - Different user roles for different parts

Windows Authentication and add Authorization Roles through database - MVC asp.net

ASP.NET Core 2.0 Identity update user roles only after re-authorization

How can I implement Claims-Based Authorization with ASP.NET WebAPI without using Roles?

Role-based authorization in ASP.NET Web API - how to set roles on the principal?

IP Based User Authorization in MVC4