. net FormsAuthentication和HttpContext.Current.User.Identity.

本文关键字:User Identity Current HttpContext FormsAuthentication net | 更新日期: 2023-09-27 18:07:58

我试图创建一个简单的设置,用户导航到一个页面,如果他们没有身份验证,采取登录页面。如果用户输入了正确的用户名和密码,他/她将被带回到第一页,在那里他们可以向SQL数据库添加数据。不幸的是,到目前为止,当用户通过身份验证时,他们会从第一页返回到登录页(例如,用户没有经过身份验证)。下面是我的代码:

第一页中适用的代码(用户可以在其中输入数据)

protected void Page_Load(object sender, EventArgs e)
{
    /*Make sure the user is authenticated.  If not, redirect them to the Login page*/
    if (!HttpContext.Current.User.Identity.IsAuthenticated)
        FormsAuthentication.RedirectToLoginPage();
    else
        LabelMsg.Text = "Authenticated: " + HttpContext.Current.User.Identity.IsAuthenticated.ToString();
}//end Page_Load()

登录页面适用代码:

 using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                sda.SelectCommand = myCommand;
                DataTable dt = new DataTable();
                sda.Fill(dt);
                GridView GridViewBookList = new GridView();
                GridViewBookList.DataSource = dt;
                GridViewBookList.DataBind();
                if (GridViewBookList.Rows.Count > 0)
                {
                    FormsAuthentication.SetAuthCookie("admin", true);
                    FormsAuthentication.RedirectFromLoginPage("admin", true);
                }
                else
                    LabelMsg.Text = "Incorrect username or password";
            }

网络。配置块

<location path="~/whatsnew/add-newbook.aspx">
<!--Unauthenticated users cannot access this page-->
<system.web>
  <authentication mode="Forms">
    <!--.NEWBOOK is the name of the cookie used in authorization-->
    <forms loginUrl="~/whatsnew/login.aspx" defaultUrl="~/default.aspx" requireSSL="true" name=".NEWBOOK"/>
  </authentication>
  <authorization>
    <deny users="?"/>
    <allow roles="admin"/>
  </authorization>
</system.web>

. net FormsAuthentication和HttpContext.Current.User.Identity.

我认为你需要检查请求。代码中的IsAuthenticated。如果你想使用HttpContext.Current.User。IsAuthenticated,根据我的经验,我必须通过在登录页面中这样设置它:

string username = "My username";
string[] roles = new string[] {"Role1", "Role2"};
HttpContext.Current.User = 
   new GenericPrincipal(new GenericIdentity(userName), roles);

我可以看到你在做简单的表单认证。你试过添加WebSecurity吗?登录前设置cookie?

WebSecurity.Login("admin", pwd, True);
FormsAuthentication.SetAuthCookie("admin", true);
FormsAuthentication.RedirectFromLoginPage("admin", true);