claim or role based access

M J 661 Reputation points
2023-02-15T20:31:54.2433333+00:00

I have a section of the site that is restricted to our younger members and sections that are restricted to adult members only. The adult members are NOT allowed to go onto the youth section unless also a parent or supervisor. Parents and adult supervisors are allowed on the youth site. Youth are restricted from the adult content section.

people that are member may have multiple roles for example I have Member, Adult Member, Boardmember, Administrator, Webmaster roles

I have these roles set up

  • Visitior -- can register but cannot visit restricted member only pages.
  • Member -- have access to member restricted pages can request games
  • Adult Member -- have access to adult member pages cannot visit youth member pages
  • Youth Member -- have access to youth member pages cannot access adult member pages
  • Parent of Youth -- can access youth member pages even if not a member but do not have access to other member pages
  • Youth Supervisor -- can access youth membere pages
  • Administrator -- has access to everything
  • Webmaster -- has access to everything
  • Boardmember -- has access to membership section of admin side
  • Newsletter Editor -- has access to newsletter section of admin side
  • Event Coordinator -- has access to Events and speakers section of admin side
  • Games Librarian -- has access to games section of admin side - can add new games/mark games as checked out or as returned

My question is when a person is logged in and tries to access a page that they are not in correct role for I want to take them to a page that says they are unauthorized to access that page. I have a view in Errors Controller called NotAuthorized.cshtml that i would like to take them to.

Right now my controller code says

namespace MyNamespace.Areas.Members.Views
{
  [Authorize(Roles = "Youth Member", "Parent of Youth", "Youth Supervisor", "Administrator","Webmaster")]
  
   public ActionResult Index()
   {
       return View();
   }

}

but when I am testing it takes me to the login page when I login as a user that does not have access trying to access one of the restricted pages. So what do I need to change?

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,256 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. SurferOnWww 1,911 Reputation points
    2023-02-16T01:11:42.71+00:00

    My question is when a person is logged in and tries to access a page that they are not in correct role for I want to take them to a page that says they are unauthorized to access that page.

    What is your authentication system? If you use the ASP.NET Core Identity the user will be automatically redirected to the Account/AccessDenied page by the framework when [Authorize(Roles ="xxx")] is put on the controller / action method and the user do not have the xxx role.

    AccessDenied


  2. QiYou-MSFT 4,306 Reputation points Microsoft Vendor
    2023-02-16T07:57:09.85+00:00

    Hi @M J

    You just need to make a feature class yourself.

    Code:

    //This method is mainly where the authorization verification logic is implemented
    public class MyAuthorizeAttribute : AuthorizeAttribute
        {
           
            protected override bool AuthorizeCore(HttpContextBase httpContext)
            {
                bool result = false;
                if (httpContext == null)
                {
                    throw new ArgumentNullException("httpContext");
                }
                string[] roles = Roles.Split(',');
                if (!httpContext.User.Identity.IsAuthenticated)
                    return false;
                foreach (string r in roles)
                {
                    if (httpContext.User.IsInRole(r))
                    {
                        result = true;
                        break;
                    }
                }
                if (!result)
                {
                    httpContext.Response.StatusCode = 403;//indicates no access
                
                }
                return result;
            }
    //This function handles the logic without permission
            protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
            {
                base.HandleUnauthorizedRequest(filterContext);
                if (filterContext == null)
                {
                    throw new ArgumentNullException("filterContext");
                }
                else if (filterContext.HttpContext.Response.StatusCode == 403)
                {
                    filterContext.HttpContext.Response.Write("<script> self.location='Error';;</script>");
                    filterContext.HttpContext.Response.End();
                   //The purpose of the following sentence is to make the program not continue to execute functions modified by MyAuthorize when it does not have access.
                  //For example, when we visit the contact page, if we do not have permission, do not continue to execute Home/Contact.
                    filterContext.Result = new EmptyResult();
                }
            }
        }
    

    The order in which the above 3 functions are executed is OnAuthorization--->AuthorizeCore--->HandleUnauthorizedRequest

    For Example

    Name1 role: employee

    Name2 role: manager

    [MyAuthorize(Roles = "employee")]
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
                return View();
            }
    public ActionResult Error()
            {
                ViewBag.Message = "Your contact page.";
                return View();
            }
    

    Test2_16

    Best Regards

    Qi You


    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.