IsInRole()方法不起作用?

时间:2014-04-21 14:58:34

标签: c# asp.net

我根据这篇文章创建了身份验证登录:
http://www.codeproject.com/Articles/2905/Role-based-Security-with-Forms-Authentication
一切正常,我可以根据用户登录,但我有IsInRole方法的问题。如果我以任何角色登录,则Adminlink仍会向所有用户显示。我刚才做的几乎和上面的文章一样。

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;

                    // Get the stored user-data, in this case, our roles
                    string userData = ticket.UserData;
                    string[] roles = userData.Split(',');
                    HttpContext.Current.User = new GenericPrincipal(id, roles);
                }
            }
        }
    }

Web.config的代码

<configuration>
  <connectionStrings>
    <add name="databasestring" connectionString="Data Source=USER-PC;Initial Catalog=database;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <authentication mode="Forms">
     <forms name="MYWEBAPP.ASPXAUTH"
         loginUrl="login.aspx"
         protection="All"
           path="/"/>
     </authentication>
    <authorization>
      <allow users="*"/>
       </authorization>
  </system.web>
  <location path="admin">
    <system.web>
      <authorization>
        <!-- Order and case are important below -->
        <allow roles="Admin"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="librarian">
    <system.web>
      <authorization>
        <!-- Order and case are important below -->
        <allow roles="Librarian"/>
          <deny users="*"/>
      </authorization>
    </system.web>
  </location>
</configuration>

登录按钮的代码:

protected void btnLogin_Click(object sender, EventArgs e)
    {
            // Initialize FormsAuthentication, for what it's worth
            FormsAuthentication.Initialize();

            // Create our connection and command objects
            SqlConnection conn =
             new SqlConnection("Data Source=USER-PC;Initial Catalog=database;Integrated Security=True");
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "SELECT UserType FROM users WHERE UserID=@UserID AND UserPassword=@UserPassword";

            // Fill our parameters
            cmd.Parameters.Add("@UserID", SqlDbType.NVarChar, 64).Value = UserID.Value;
            cmd.Parameters.Add("@UserPassword", SqlDbType.NVarChar, 128).Value = UserPassword.Value; // Or "sha1"

            // Execute the command
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                // Create a new ticket used for authentication
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                   1, // Ticket version
                   UserID.Value, // Username associated with ticket
                   DateTime.Now, // Date/time issued
                   DateTime.Now.AddMinutes(30), // Date/time to expire
                   true, // "true" for a persistent user cookie
                   reader.GetString(0), // User-data, in this case the roles
                   FormsAuthentication.FormsCookiePath);// Path cookie valid for

                // Encrypt the cookie using the machine key for secure transport
                string hash = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(
                   FormsAuthentication.FormsCookieName, // Name of auth cookie
                   hash); // Hashed ticket

                // Set the cookie's expiration time to the tickets expiration time
                if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

                // Add the cookie to the list for outgoing response
                Response.Cookies.Add(cookie);

                // Redirect to requested URL, or homepage if no previous page
                // requested
                string returnUrl = Request.QueryString["/WebForm2.aspx"];
                if (returnUrl == null) returnUrl = "/WebForm2.aspx";

                // Don't call FormsAuthentication.RedirectFromLoginPage since it
                // could
                // replace the authentication ticket (cookie) we just added
                Response.Redirect(returnUrl);
            }
            else
            {
                // Never tell the user if just the username is password is incorrect.
                // That just gives them a place to start, once they've found one or
                // the other is correct!
                ErrorLabel.Text = "Username / password incorrect. Please try again.";
                ErrorLabel.Visible = true;
            }

            reader.Close();
            conn.Close();
        }
 }

WebForm2.aspx的代码

protected void Page_Load(object sender, EventArgs e)
    {
        if (User.IsInRole("Admin"))
        {
            AdminLink.Visible = true;
        }
    }

1 个答案:

答案 0 :(得分:0)

身份验证通常使用Cookie,如果是,则需要完整的服务器\客户端往返才能获得完整的可靠数据。您是否在检查角色状态之前验证执行往返的用户?

另外,你在哪里设置&#34; adminlink&#34;能见度属性?您使用的是LoginView控件,还是其他一些显示\隐藏此数据的方法?请提供一些基本的代码示例。


对编辑的回应: 我无法在任何地方看到您将此链接的可见性设置为false。在条件语句中将该逻辑添加到您的其他...和\或设置&#34; visible = false&#34;在您的HTML标记中,看看是否修复了它。

如果没有解决问题,您是否设置了断点以查看IsInRole如何返回?你期望它会回来是对还是错?