No login error text for role based authentication

2019-08-16 03:19发布

问题:

I have an ASP.NET Role/Membership based forms authentication site. There's a subfolder and its pages which can be accessed only by a certain role. The problem is, login page does not display any error message if any user from non-allowed role group logins in login page. I mean, when a user from AllowedRole logins, the login page redirects the user correctly to the protected page, but when a user from NonAllowedRole tries to login, he/she correctly logs in but there are no error messages displayed, the user is back to the login page without any information. I do have a FailureText set in Login form but it's not displayed. loginForm.LoginError event is also doesn't get raised. I tried this code but it doesn't display either:

protected void frmLogin_LoggedIn(object sender, EventArgs e)
        {
            if (!User.IsInRole("AllowedRole"))
                frmLogin.FailureText = "Access denied.";
                //Label1.Text = "Access denied."; //doesn't work either
        }

What am I doing wrong?

回答1:

I don't know where to find the documentation to support this. This answer is based on observation of the behavior I've seen io apps I've written.

The login page is exluded from the allowed access rules. It needs to be. Say you have a site where the whole site disallows anonymous users, even at the root level. The users need to be able to access the login page to be able to log in.

To resolve your dilemma you would need to add a label (I would call it lblError) and in your Page_Load, add the following (C# example code):

if(User.IsLoggedIn)
{
   If(!User.IsInRole("AllowedRole")
   {
      lblError.Text = "Access denied.";
   }


}

Added

Gving this more thought, the reason there is no error in the login page is that the error is happening when the user attempts to access the protected page, not within the login page.

However, I believe my suggestion will work for your situation as well.



回答2:

On thing you can do is check the ReturnUrl query string parameter and if it's you "denied" folder, redirect the user to either an error page or an allowed login page. Like this:

protected void frmLogin_LoggedIn(object sender, EventArgs e)
{
    if (!User.IsInRole("AllowedRole") && 
        InRestrictedArea(Request.QueryString["ReturnUrl"]))
    {
        Response.Redirect("Not-Allowed-Here.aspx");
    }
}

Define InRestrictedArea to check if the requested area is where they aren't allowed.