首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IsInRole()方法不工作吗?

IsInRole()方法不工作吗?
EN

Stack Overflow用户
提问于 2014-04-21 22:58:34
回答 1查看 392关注 0票数 0

我基于这篇文章创建身份验证登录:

http://www.codeproject.com/Articles/2905/Role-based-Security-with-Forms-Authentication

一切正常,我可以根据用户登录,但我的IsInRole方法有问题。如果我以任何角色登录,Adminlink仍然对所有用户显示。我只是做了与上面的文章几乎相同的事情。

Global.asax的代码

代码语言:javascript
复制
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的代码

代码语言:javascript
复制
<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>

登录按钮代码:

代码语言:javascript
复制
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的代码

代码语言:javascript
复制
protected void Page_Load(object sender, EventArgs e)
    {
        if (User.IsInRole("Admin"))
        {
            AdminLink.Visible = true;
        }
    }
EN

回答 1

Stack Overflow用户

发布于 2014-04-21 23:20:17

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

另外,如何设置"adminlink“可见性属性?您是否正在使用LoginView控件,或其他显示/隐藏此数据的方法?请提供一些基本的代码示例。

对编辑的响应:我看不出您在哪里将此链接的可见性设置为false。在条件语句中将该逻辑添加到else中。或者在HTML标记中设置"visible=false“,看看是否可以修复它。

如果这还不能解决问题,那么您是否设置了断点来查看IsInRole返回的结果?当你期望它返回时,它是真的还是假的?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23199907

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档