简体   繁体   中英

Authorization in Web.Config file not working after proper credentials

I want whenever a user if not logged in, and if he puts the page name directly in the url he should be directed to login page of the site.

I gaved authentication in my web.config file as below:-

 <authentication mode="Forms">
  <forms loginUrl="~/Login.aspx" timeout="2880" defaultUrl="~/" />
</authentication> 
<authorization>
  <deny users="?"/>
</authorization>

But still when I login with my correct credentials, it still stays in the login page.

Also see my login button code:-

 protected void btnSubmit_Click(object sender, EventArgs e)
    {
        String LoginID = txtUsername.Text.Trim().ToLower();
        String LoginPassword = txtPassword.Text.Trim();

        SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
        conn.Open();
        SqlCommand cmd = new SqlCommand("select username,password,usertype from tbl_User where username =@username and password=@password and Active= 1 ", conn);
        FormsAuthentication.SetAuthCookie("2", false);
        cmd.Parameters.AddWithValue("@username", txtUsername.Text);
        cmd.Parameters.AddWithValue("@password", txtPassword.Text);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt != null && dt.Rows.Count > 0)
        {
            if (dt.Rows[0]["usertype"].ToString() == "0") //SuperAdmin
            {
                Session["User"] = "0";
                Response.Redirect("csrpage.aspx");
            }
            else if (dt.Rows[0]["usertype"].ToString() == "1") // Admin
            {
                Session["User"] = "1";
                Response.Redirect("Admin.aspx");
            }
            else if (dt.Rows[0]["usertype"].ToString() == "2") // User
            {
                Session["User"] = "2";
                Response.Redirect("User.aspx");
            }
        }
        else
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
        }

    }

Please help.

当确认用户名和密码正确时,您需要调用FormsAuthentication.SetAuthCookie("username", false);

Got the solution from the below link:-

Authentication issue The main part for me in that was below added code:-

<location path="User">
   <system.web>
   <authorization>
   <deny users="?"/>
    </authorization>
       </system.web>
 </location>

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