簡體   English   中英

<authentication mode=“Forms”>不起作用?

[英]<authentication mode=“Forms”> doesnt work?

我有一個登錄頁面,用戶可以在其中登錄。使用正確的詳細信息登錄時,他們將被發送到主管理頁面。 如果他們無法登錄,他們將停留在登錄頁面上。 我想做的是,如果是隨機用戶,則在他們未登錄時將輸入管理員頁面的URL,而他們正在重定向到登錄頁面。

我了解我必須在母版頁或webconfig中完成!!! 我有一個主要的管理頁面和其他一些管理頁面。

有小費嗎?

我試圖將其插入到我的webconfig中:

<authentication mode="Forms">
    <forms loginUrl="InnUtlogging.aspx" timeout="2880"/>
  </authentication>

這是我的“登錄”按鈕的代碼(在登錄頁面上);

protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True");
        con.Open();
        SqlCommand cmd = new SqlCommand("select * FROM Ansatt WHERE epost='" + brukernavn.Text + "' and passord='" + passord.Text + "'");
        cmd.Connection = con;
        int OBJ = Convert.ToInt32(cmd.ExecuteScalar());

        if (OBJ > 0)

            {
            Session["name"] = brukernavn.Text;
            Response.Redirect("KunstnerAdmin.aspx");
        }
        else
            {
                melding.Text = "Feil brukernavn/passord";
            }
        if (brukernavn.Text == "")
        {
            melding.Text = "Du må fylle inn brukernavn";

        }
        if (passord.Text == "")
        {
            melding.Text = "Du må fylle inn passord";
        }
        }

“登錄”頁面上的代碼適用於該頁面,但是我實際上想檢查用戶是否在母版頁面中登錄。 我可以在母版頁中做些什么來激活表單身份驗證?

您的代碼缺少FormsAuthentication的許多內容。

首先,該代碼容易受到SQL Injection攻擊 您想考慮使用Parameterized Query

登入方式

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

Global.asax.cs

您需要這樣做,以便從Cookie中檢索用戶名,並將其保存在IPrincipal Object中。

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;
    }
}

web.config

<authentication mode="Forms">
   <forms loginUrl="~/InnUtlogging.aspx" />
</authentication>

用法

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

這是檢查用戶是否通過身份驗證的方法。

HttpContext.Current.User.Identity.IsAuthenticated

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM