Application_AuthenticateRequest在创建Forms身份验证票证之前首先执行

时间:2015-06-07 15:04:54

标签: c# asp.net forms-authentication global-asax

我在使用基于角色的安全性与表单身份验证时遇到问题,每次我尝试第一次登录时票证似乎没有UserData,因为Application_Authenticate请求首先执行,而我的if语句没有执行,因为角色是在第一次回帖后没有。

请帮忙!

我的登录点击事件:

 protected void signin_click(object sender, EventArgs e)
{
    if (con.State == ConnectionState.Closed)
    {
        con.Open();
    }
    HashData ob = new HashData();//Custom Class used for Hashing Passwords
    SqlCommand cmd = new SqlCommand("Logincheck", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@username", SqlDbType.VarChar, 50).Value = txt_username.Text.Trim();
    string pass = ob.Encrypt(txt_pass.Text.Trim());
    cmd.Parameters.Add("@password", SqlDbType.VarChar, 50).Value = pass;
    SqlParameter result = new SqlParameter("@result", SqlDbType.Int) { Direction = ParameterDirection.Output };
    SqlParameter userrole = new SqlParameter("@userrole", SqlDbType.VarChar,50) { Direction = ParameterDirection.Output };
    cmd.Parameters.Add(result); cmd.Parameters.Add(userrole);

    cmd.ExecuteNonQuery();
    int rslt = Convert.ToInt32(result.Value);
    if (rslt == -1)
    {
        string message = "Login Failed";
        string url = "Login.aspx";
        string script = "window.onload = function(){ alert('";
        script += message;
        script += "');";
        script += "window.location = '";
        script += url;
        script += "'; }";
        ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
    }
    string u_role = userrole.Value.ToString();
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
        (1, txt_username.Text.Trim(), DateTime.Now,
        DateTime.Now.AddMinutes(30), false, u_role,
        FormsAuthentication.FormsCookiePath);
    string hash = FormsAuthentication.Encrypt(ticket);
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
    if (ticket.IsPersistent)
    {
        cookie.Expires = ticket.Expiration;
    }
    Response.Cookies.Add(cookie);
    if (User.IsInRole("admin"))
    {
        Response.Redirect("~/Admin/Admin.aspx");
    }
    if (User.IsInRole("manager"))
    {
        Response.Redirect("~/Manager/Manager.aspx");
    }
    if (User.IsInRole("teamlead"))
    {
        Response.Redirect("~/Teamlead/Teamlead.aspx");
    }
    if (User.IsInRole("qa"))
    {
        Response.Redirect("~/Default.aspx");
    }
    cmd.Dispose();
    con.Close();
}

我的Global.ASAX文件

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    if (HttpContext.Current.User != null)
    {
        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            if (HttpContext.Current.User.Identity is FormsIdentity)
            {
                FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                FormsAuthenticationTicket ticket = id.Ticket;
                string userData = ticket.UserData;
                string[] roles = userData.Split(',');
                HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

自己找到解决方案,User.IsInRole将在表单身份验证票证和我们的主要对象生成后生效,即。回发后。

因此,为了解决这个问题,我只使用数据库中的静态角色来重定向。

 protected void signin_click(object sender, EventArgs e)
{
    if (con.State == ConnectionState.Closed)
    {
        con.Open();
    }
    HashData ob = new HashData();//Custom Class used for Hashing Passwords
    SqlCommand cmd = new SqlCommand("Logincheck", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@username", SqlDbType.VarChar, 50).Value = txt_username.Text.Trim();
    string pass = ob.Encrypt(txt_pass.Text.Trim());
    cmd.Parameters.Add("@password", SqlDbType.VarChar, 50).Value = pass;
    SqlParameter result = new SqlParameter("@result", SqlDbType.Int) { Direction = ParameterDirection.Output };
    SqlParameter userrole = new SqlParameter("@userrole", SqlDbType.VarChar,50) { Direction = ParameterDirection.Output };
    cmd.Parameters.Add(result); cmd.Parameters.Add(userrole);

    cmd.ExecuteNonQuery();
    int rslt = Convert.ToInt32(result.Value);
    if (rslt == -1)
    {
        string message = "Login Failed";
        string url = "Login.aspx";
        string script = "window.onload = function(){ alert('";
        script += message;
        script += "');";
        script += "window.location = '";
        script += url;
        script += "'; }";
        ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
    }
    string u_role = userrole.Value.ToString();
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
        (1, txt_username.Text.Trim(), DateTime.Now,
        DateTime.Now.AddMinutes(30), false, u_role,
        FormsAuthentication.FormsCookiePath);
    string hash = FormsAuthentication.Encrypt(ticket);
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);

    if (ticket.IsPersistent)
    {
        cookie.Expires = ticket.Expiration;
    }
    Response.Cookies.Add(cookie);
   // Response.Redirect("Redirecting.aspx");

    if (u_role == "admin")
    {
        Response.Redirect("~/Admin/Admin.aspx");
    }
    if (u_role == "admin" || u_role == "manager")
    {
        Response.Redirect("~/Manager/Manager.aspx");
    }
    if (u_role == "teamlead" || u_role == "admin" || u_role == "manager")
    {
        Response.Redirect("~/Teamlead/Teamlead.aspx");
    }
    if (u_role == "qa")
    {
        Response.Redirect("Default.aspx");
    }
    cmd.Dispose();
    con.Close();
}

现在工作正常,

感谢。