Role-based authorization from Database?

Brian 161 Reputation points
2021-11-05T19:01:01.927+00:00

I'm working on a large .NET 5 razor pages application with a reporting feature (about 45 reports) and about 9 different user roles. Each user role has access to certain reports. I believe I can allow and restrict access using role page authorization in my Page Model:

[Authorize(Roles = "Role1, Role2, Role4")]
public class public class Report1 : PageModel
{
}

However, instead of manually coding each role like this for 45 different reports, can I pull the roles from my database? For simplicity, lets stay I have a Roles table which stores data as:

Report Role
Report1 Role1
Report1 Role2
Report1 Role4

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,209 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,021 Reputation points Microsoft Vendor
    2021-11-08T08:59:59.847+00:00

    Hi @Brian ,

    You can create a custom Authorization attribute, in its OnAuthorization method, you could get the current login username, then based on the username to find the relates roles and check whether it has permission to access the action method.

    Please refer the following sample code:

    Create a RoleAuthorizeAttribute:

       [AttributeUsage(AttributeTargets.Class |AttributeTargets.Method)]  
        public class RoleAuthorizeAttribute : Attribute, IAuthorizationFilter  
        {  
            public string currentReport;  
            public RoleAuthorizeAttribute(string CurrentReport)  
            {  
                currentReport = CurrentReport;  
            }  
      
            /// <summary>    
            /// This will Authorize User    
            /// </summary>    
            /// <returns></returns>    
            public async void OnAuthorization(AuthorizationFilterContext filterContext)  
            {    
                var _dbcontext = filterContext.HttpContext  
                .RequestServices  
                .GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;  
      
                if (filterContext != null)  
                {  
                    //get current login username  
                    var username = filterContext.HttpContext.User.Identity.Name;  
      
                    //get the current report name.  
                    var reportname = currentReport;   
      
                    //get current user  
                    //var users = _dbcontext.Users.Where(c => c.UserName == username).FirstOrDefault();  
      
                    // according to the username and report name to query database via the _dbcontext, and then check whether the user has permission to access the report.  
                    //based on the result to continue or return the Unauthorized message.  
                    if (username != null)  
                    {   
                           //validate success  
                    }  
                    else  
                    {  
                        filterContext.Result = new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized };  
                    }  
                }  
            }   
        }  
    

    Apply the custom attribute on the action method:

        [RoleAuthorize("report1")]  
        public IActionResult Privacy()  
        {  
           
            return View();  
        }  
    

    The screenshot as below:

    147332-1.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments