C# 应用程序\u AuthenticateRequest不断调用无限重定向

C# 应用程序\u AuthenticateRequest不断调用无限重定向,c#,asp.net,form-authentication,C#,Asp.net,Form Authentication,这是我生命的延续 我曾尝试使用内置的ASP登录机制,但它不适合我。主要的原因是,我被要求保持它的简单明了 现在,我的立场是: Web.config <system.web> <sessionState timeout="10" /> <authentication mode="Forms"> <forms timeout="30" loginUrl="~/SecuredArea/LogInOut/log-in.aspx"

这是我生命的延续

我曾尝试使用内置的ASP登录机制,但它不适合我。主要的原因是,我被要求保持它的简单明了

现在,我的立场是:

Web.config

<system.web>
    <sessionState timeout="10" />

    <authentication mode="Forms">
        <forms timeout="30" loginUrl="~/SecuredArea/LogInOut/log-in.aspx" />
    </authentication>

    <authorization>
        <allow users="?" />
    </authorization>

</system.web>

<location path="SecuredArea/AdminArea">
    <system.web>
        <authorization>
            <allow roles="administrators" />
            <deny users="*" />
        </authorization>
    </system.web>
</location>

<location path="SecuredArea/EmployeeArea">
    <system.web>
        <authorization>
            <allow roles="employees" />
            <deny users="*" />
        </authorization>
    </system.web>
</location>
我在这里对混乱的代码进行了注释,因为我不想访问DB并在这里遍历所有可能的员工。对于管理员帐户,这很容易,但对于员工帐户,这是不可能的

登录.aspx.cs

protected void ButtonLogOn_Click(object sender, EventArgs e)
{
    if (String.IsNullOrEmpty(txtUserName.Value.Trim()) || String.IsNullOrEmpty(txtPassword.Value.Trim()))
    {
        labelMessage.Text = MessageFormatter.GetFormattedErrorMessage("You can login using a username and a password associated with your account. Make sure that it is typed correctly.");
    }
    else
    {
        try
        {
            LoginPage loginBack = new LoginPage();
            int result = loginBack.VerifyCredentials(txtUserName.Value.Trim(), txtPassword.Value.Trim());

            switch (result)
            {
                case -9:
                //System needs provisioning
                labelMessage.Text = MessageFormatter.GetFormattedErrorMessage("SMB Password Reset System need provisioning. Login as Administrator.");
                break;

                case 0:
                //Enroll-able User
                // Success, create non-persistent authentication cookie.
                FormsAuthentication.SetAuthCookie(txtUserName.Value.Trim(), false);

                FormsAuthenticationTicket ticketEmployee =
                    new FormsAuthenticationTicket(
                        1,                                                      // version
                        txtUserName.Value.Trim(),           // get username  from the form
                        DateTime.Now,                                   // issue time is now
                        DateTime.Now.AddMinutes(10),    // expires in 10 minutes
                        false,                                              // cookie is not persistent
                        "employees");

                HttpCookie cookieEmployee = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticketEmployee));
                Response.Cookies.Add(cookieEmployee);

                SiteLogin.PerformAuthentication(txtUserName.Value.Trim(), false);
                break;

                case 1:
                //User not in required directory group
                labelMessage.Text = MessageFormatter.GetFormattedErrorMessage("You cannot login because you are not authorized.");
                break;

                default:
                //Bad name and/or password                              
                labelMessage.Text = MessageFormatter.GetFormattedErrorMessage("You can login using a username and a password associated with your account. Make sure that it is typed correctly.");
                break;
            }
        }
        catch (MessageSecurityException expMse)
        {
            //Bad name and/or password
            Debug.WriteLine("Error: " + expMse.Message);
            labelMessage.Text = MessageFormatter.GetFormattedErrorMessage("You can login using a username and a password associated with your account. Make sure that it is typed correctly.");
        }
        catch (Exception exp)
        {
            labelMessage.Text = MessageFormatter.GetFormattedErrorMessage("Some general error has occured. Message reads: " + exp.Message);
        }
    }
}

protected void ButtonAdminLogOn_Click(object sender, EventArgs e)
{
    if (String.IsNullOrEmpty(txtUserName.Value) || String.IsNullOrEmpty(txtPassword.Value))
        labelMessage.Text = MessageFormatter.GetFormattedErrorMessage("<strong>Login Please!</strong><hr/>You can login using a username and a password associated with your account. Make sure that it is typed correctly.");
    else
    {
        //if the log-in is successful
        if (txtUserName.Value == "admin" && txtPassword.Value == "AlphaBeta")
        {
            // Success, create non-persistent authentication cookie.
            FormsAuthentication.SetAuthCookie(txtUserName.Value.Trim(), false);

            FormsAuthenticationTicket ticketAdmin =
                new FormsAuthenticationTicket(
                    1,                                                      // version
                    txtUserName.Value.Trim(),           // get username  from the form
                    DateTime.Now,                                   // issue time is now
                    DateTime.Now.AddMinutes(10),    // expires in 10 minutes
                    false,                                              // cookie is not persistent
                    "administrators");

            HttpCookie cookieAdmin = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticketAdmin));
            Response.Cookies.Add(cookieAdmin);

            SiteLogin.PerformAdminAuthentication(txtUserName.Value.Trim(), false);
        }
        else
        {
            labelMessage.Text = MessageFormatter.GetFormattedErrorMessage("<strong>Login Failed!</strong><hr/>The username and/or password you entered do not belong to any Administrator account on our system.<br/>You can login using a username and a password associated with your account. Make sure that it is typed correctly.");
        }
    }
}
public sealed class SiteLogin
{       
    public static void PerformAuthentication(string userName, bool remember)
    {
        FormsAuthentication.RedirectFromLoginPage(userName, remember);

        if (HttpContext.Current.Request.QueryString["ReturnUrl"] == null)
        {
            RedirectToDefaultPage();
        }
        else
        {
            HttpContext.Current.Response.Redirect(HttpContext.Current.Request.QueryString["ReturnUrl"]);
        }
    }

    public static void PerformAdminAuthentication(string userName, bool remember)
    {
        FormsAuthentication.RedirectFromLoginPage(userName, remember);

        if (HttpContext.Current.Request.QueryString["ReturnUrl"] == null)
        {
            RedirectToAdminDefaultPage();
        }
        else
        {
            HttpContext.Current.Response.Redirect(HttpContext.Current.Request.QueryString["ReturnUrl"]);
        }
    }

    /// <summary>
    /// Redirects the current user based on role
    /// </summary>
    public static void RedirectToDefaultPage()
    {
        HttpContext.Current.Response.Redirect("~/SecuredArea/EmployeeArea/EmployeeDefaultPage.aspx");
    }

    /// <summary>
    /// Redirects the current user based on role
    /// </summary>
    public static void RedirectToAdminDefaultPage()
    {
        HttpContext.Current.Response.Redirect("~/SecuredArea/AdminArea/AdminDefaultPage.aspx");
    }

    public static void LogOff()
    {
        // Put user code to initialize the page here
        FormsAuthentication.SignOut();

        //// Invalidate roles token
        //Response.Cookies[Globals.UserRoles].Value = "";
        //Response.Cookies[Globals.UserRoles].Path = "/";
        //Response.Cookies[Globals.UserRoles].Expires = new System.DateTime(1999, 10, 12);

        //Set the current user as null
        HttpContext.Current.User = null;
    }
}
有人能确定这个问题吗?我今天真的需要结束这件事。谢谢

编辑

我使用了fiddler,我看到一旦按下login,就会创建一个无限循环。我可以通过图像显示行为:

访问安全区域时引发登录页面

输入凭证并按下登录按钮

凭证被接受并重定向回安全页面,然后再次重定向到登录,以此类推


我选择fiddler的Cookies选项卡,因为在那里检测到明显的更改。

在您的SiteLogin和AdminLogin页面中,您可以使用FormsAuthentication.RedirectFromLoginPage(用户名,请记住)开始执行身份验证功能;-这会导致重定向回ReturnUrl页面,因此我的第一个想法是,您访问该页面,重定向到此登录页面,然后该代码将您重定向回第一个页面,并且,由于您尚未登录,它将您重定向回此处,依此类推!试着从这些行开始注释,看看这是否是问题所在。
SiteLogin
只是一个用于隐藏重定向指令的实用程序类。问题是,在
PerformAdminAuthentication()
方法中,有一个if-else。我总是在else部分登陆,这意味着我没有登录。或者这就是我从互联网上推断出来的。同意,但是你在if-else之前做了RedirectFromLoginPage,所以我想知道这是否是导致你反复出现问题的原因。
public sealed class SiteLogin
{       
    public static void PerformAuthentication(string userName, bool remember)
    {
        FormsAuthentication.RedirectFromLoginPage(userName, remember);

        if (HttpContext.Current.Request.QueryString["ReturnUrl"] == null)
        {
            RedirectToDefaultPage();
        }
        else
        {
            HttpContext.Current.Response.Redirect(HttpContext.Current.Request.QueryString["ReturnUrl"]);
        }
    }

    public static void PerformAdminAuthentication(string userName, bool remember)
    {
        FormsAuthentication.RedirectFromLoginPage(userName, remember);

        if (HttpContext.Current.Request.QueryString["ReturnUrl"] == null)
        {
            RedirectToAdminDefaultPage();
        }
        else
        {
            HttpContext.Current.Response.Redirect(HttpContext.Current.Request.QueryString["ReturnUrl"]);
        }
    }

    /// <summary>
    /// Redirects the current user based on role
    /// </summary>
    public static void RedirectToDefaultPage()
    {
        HttpContext.Current.Response.Redirect("~/SecuredArea/EmployeeArea/EmployeeDefaultPage.aspx");
    }

    /// <summary>
    /// Redirects the current user based on role
    /// </summary>
    public static void RedirectToAdminDefaultPage()
    {
        HttpContext.Current.Response.Redirect("~/SecuredArea/AdminArea/AdminDefaultPage.aspx");
    }

    public static void LogOff()
    {
        // Put user code to initialize the page here
        FormsAuthentication.SignOut();

        //// Invalidate roles token
        //Response.Cookies[Globals.UserRoles].Value = "";
        //Response.Cookies[Globals.UserRoles].Path = "/";
        //Response.Cookies[Globals.UserRoles].Expires = new System.DateTime(1999, 10, 12);

        //Set the current user as null
        HttpContext.Current.User = null;
    }
}
<div class="info-area">
    <asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
        <LoggedInTemplate>
            Welcome <span class="bold">
                <asp:LoginName ID="HeadLoginName" runat="server" />
            </span>! |
        </LoggedInTemplate>
    </asp:LoginView>
    <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Logout" LogoutPageUrl="~/SecuredArea/LogInOut/log-out.aspx" />
</div>