简体   繁体   中英

AuthorizeAttribute doesn't work when refresh the page

I have some problem with authorization:

The AuthorizeWebForm codes work when loading the page, I am not in the admin group so I don't have the access, which is great. But when I refresh the page, I have access to the page, and the code AuthorizeWebFormAttribute doesn't run when refresh. Any solution to this?

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeWebFormAttribute : System.Attribute
{
    public AuthorizeWebFormAttribute(string Roles = null)
    {
        IPrincipal user = HttpContext.Current.User;
        if (user.Identity.IsAuthenticated)
        {
            if (Roles == null)
                return;

            if (user.IsInRole("admin"))
                return;

            string[] roleArray = Roles.Split(',');
            foreach (var role in roleArray)
            {
                if (user.IsInRole(role))
                    return;
            }
        }
        HttpContext.Current.Server.TransferRequest("~/Unauthorized", false);
    }
}

namespace Crew
{
    [AuthorizeWebForm("admin")]
    protected void Page_Load(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Session["EmpNo_User"].ToString()))
        {
            Response.Redirect("~/ErrorPage.aspx?CustError=This page expired. Please close the broswer and open again.");
        }
        Page.MaintainScrollPositionOnPostBack = true;
    }

}

Thank you very much!

You are reinventing the wheel here. There's a perfectly good AuthorizeAttribute class you can use: https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.authorizeattribute?view=aspnet-mvc-5.2

Also take a look at https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-security/roles/role-based-authorization-cs for role-based security in general.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM