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:
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