Determine if user can access the requested page?

后端 未结 7 1470
小鲜肉
小鲜肉 2021-01-05 10:36

I have an ASP.Net website with multiple roles, each with access to a separate directory (i.e. admin users can access /admin, shoppers can access /shop etc), using a shared l

7条回答
  •  渐次进展
    2021-01-05 11:38

    One approach would be to override OnLoad of your aspx forms and check if the authenticated user is allowed access to the resource based on the role. So you create a BasePage.cs (in which you define a class BasePage which inherits from System.Web.UI.Page) for example from which all your Forms (aspx) inherit, in which you do this:

    protected override void OnLoad(EventArgs e)
    {
        InitializeSitemap();
        if (SiteMap.CurrentNode != null)
        {
            if (!UrlHelper.IsAnonymousAllowed(SiteMap.CurrentNode) && (!HttpContext.Current.User.Identity.IsAuthenticated || !UrlHelper.IsAccesible(SiteMap.CurrentNode)))
            {
                // You can redirect here to some form that has a custom message
                Response.Redirect("~/Forms/Logout.aspx");
    
                return;
            }
        }
        base.OnLoad(e);
    }
    

    Then in your UrlHelper class you need that IsAccessible function used above:

    public static bool IsAccesible(SiteMapNode node)
    {
        bool toRole = false;
    
        foreach (string role in node.Roles)
        {
            if (role == "*" || HttpContext.Current.User.IsInRole(role))
            {
                toRole = true;
            }
        }
    
        return toRole;
    }
    

    Here is IsAnonymousAllowed in case you wondered:

    public static bool IsAnonymousAllowed(SiteMapNode node)
    {
        return node[AllowAnonymousAttribute] != null ? bool.Parse(node[AllowAnonymousAttribute]) : false;
    }
    

提交回复
热议问题