具有动态角色的FormsAuthentication

时间:2011-07-31 08:17:02

标签: c# .net asp.net form-authentication

我有一个带有角色表和权限(每个表单的用户权限)表的应用程序,不同的角色具有不同的访问级别,每个用户对每个表单都有特定的访问权限。 我可以使用FormsAuthentication实现它吗?

谢谢

2 个答案:

答案 0 :(得分:1)

听起来您可以在这种情况下构建自定义表单身份验证提供程序。

这是一个例子 http://www.codeproject.com/KB/web-security/AspNetCustomAuth.aspx

答案 1 :(得分:1)

您必须将一个或多个列表传递给FormsAuthenticationTicket

这是完整的代码,我也添加了评论。

protected void lbtnSignIn_Click(object sender, EventArgs e)
{
 .......Login credential checking code......
 .......If the use verified, then add the roles to FormsAuthenticationTicket 
 .......I am assuming in the below code, you are getting list of roles from DB in DataTable
 String roles = String.Empty;
 if (dtblUsersRoles.Rows.Count > 0)
    {
     for (int count = 0; count < dtblUsersRoles.Rows.Count; count++)
     {
      //build list of roles in comma seperate
      roles = roles + "," + dtblUsersRoles.Rows[count]["RoleName"].ToString();
     }
    }

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, txtUserID.Text, 
DateTime.Now, DateTime.Now.AddMinutes(30), false, roles.Substring(1, roles.Length - 1), FormsAuthentication.FormsCookiePath);
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
Response.Cookies.Add(cookie);
}

然后你可以检查用户,如果他处于某个角色

 if (HttpContext.Current.User.IsInRole("Super Admin"))
 {
  ...................
 }