<authentication mode="Forms"> 不起作用?

1 c# asp.net authentication

我有一个用户可以登录的登录页面。当他们使用正确的详细信息登录时,他们会被发送到主管理页面。如果他们无法登录,他们将停留在登录页面。我想要做的是,如果随机用户在未登录时输入管理页面的 URL,则会重定向到登录页面。

\n\n

我已经明白我必须在母版页或 webconfig 中执行此操作!?!我有一个主管理页面和一些其他管理页面。

\n\n

有小费吗?

\n\n

我尝试将其插入到我的 webconfig 中:

\n\n
<authentication mode="Forms">\n    <forms loginUrl="InnUtlogging.aspx" timeout="2880"/>\n  </authentication>\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我的“登录”按钮代码(在登录页面上);

\n\n
protected void Button1_Click(object sender, EventArgs e)\n    {\n        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");\n        con.Open();\n        SqlCommand cmd = new SqlCommand("select * FROM Ansatt WHERE epost=\'" + brukernavn.Text + "\' and passord=\'" + passord.Text + "\'");\n        cmd.Connection = con;\n        int OBJ = Convert.ToInt32(cmd.ExecuteScalar());\n\n        if (OBJ > 0)\n\n            {\n            Session["name"] = brukernavn.Text;\n            Response.Redirect("KunstnerAdmin.aspx");\n        }\n        else\n            {\n                melding.Text = "Feil brukernavn/passord";\n            }\n        if (brukernavn.Text == "")\n        {\n            melding.Text = "Du m\xc3\xa5 fylle inn brukernavn";\n\n        }\n        if (passord.Text == "")\n        {\n            melding.Text = "Du m\xc3\xa5 fylle inn passord";\n        }\n        }\n
Run Code Online (Sandbox Code Playgroud)\n\n

“登录”页面上的代码适用于该页面,但我实际上想检查用户是否在母版页中登录。我可以在母版页中执行某些操作来激活表单身份验证吗?

\n

Win*_*Win 5

您的代码缺少FormsAuthentication的很多部分。

首先,代码容易受到SQL注入攻击。您要考虑使用参数化查询

登录方式

protected void Button1_Click(object sender, EventArgs e)
{
    // After validation successful 
    bool rememberMe = false; // Make it false for now
    FormsAuthentication.RedirectFromLoginPage(brukernavn.Text, rememberMe);
}
Run Code Online (Sandbox Code Playgroud)

全局.asax.cs

您需要它才能从 cookie 中检索用户名,并将其保存在 IPrincipal 对象中。

public class Global : HttpApplication
{
    private void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie decryptedCookie =
            Context.Request.Cookies[FormsAuthentication.FormsCookieName];

        FormsAuthenticationTicket ticket =
            FormsAuthentication.Decrypt(decryptedCookie.Value);

        var identity = new GenericIdentity(ticket.Name);
        var principal = new GenericPrincipal(identity, null);

        HttpContext.Current.User = principal;
        Thread.CurrentPrincipal = HttpContext.Current.User;
    }
}
Run Code Online (Sandbox Code Playgroud)

网络配置

<authentication mode="Forms">
   <forms loginUrl="~/InnUtlogging.aspx" />
</authentication>
Run Code Online (Sandbox Code Playgroud)

用法

protected void Page_Load(object sender, EventArgs e)
{
    if (User.Identity.IsAuthenticated)
    {
        string username = User.Identity.Name;
    }
}
Run Code Online (Sandbox Code Playgroud)