c# - ASP.NET MVC3 角色

标签 c# asp.net asp.net-mvc-3 roles action-filter

我目前正在使用 MVC3 框架创建一个应用程序。我了解如何将角色与过滤器一起使用,例如:

[Authorize(Roles = "Admin")]

我的问题是:

我在哪里设置角色?是在登录吗?这是如何实现的?

最佳答案

当您自己创建表单例份验证票证时,您通常会使用票证的 UserData 部分来存储与您的用户相关的信息。这可能是角色。

然后在 Application_AuthenticateRequest 事件的 Global.asax 中,您将解析您的 Forms Ticket 并将角色分配给当前的安全主体。

以下是有关不同提供商的 Forms Auth 的一些指南:

http://weblogs.asp.net/scottgu/archive/2006/02/24/ASP.NET-2.0-Membership_2C00_-Roles_2C00_-Forms-Authentication_2C00_-and-Security-Resources-.aspx

一般来说,我通常会编写自己的 System.Security.Principal.GenericPrincipal 和 System.Web.Security.FormsIdentity 来为我完成所有工作。

public class UserIdentity: System.Web.Security.FormsIdentity 
{
    public string[] Roles { get; private set; }
    public string FirstName { get; private set; }
    public string UserName { get; private set; }
    public int UserID { get; private set; }

    public UserIdentity(System.Web.Security.FormsAuthenticationTicket ticket) : base(ticket)
    {
        if (ticket.UserData != null && ticket.UserData.IndexOf("|") != -1)
        {
            string[] dataSections = ticket.UserData.Split('|');

            //Get the first name
            FirstName = dataSections.Length >= 3 ? dataSections[2] : "";

            //Get the username
            UserName = ticket.Name;

            #region Parse the UserID
            int userID = 0;
            int.TryParse(dataSections[0], out userID);
            this.UserID = userID;
            #endregion

            this.Roles = System.Text.RegularExpressions.Regex.Split(dataSections[1], ",");

        }
    }
}

public class UserPrincipal : System.Security.Principal.GenericPrincipal
{
    public UserPrincipal(UserIdentity identity) : base(identity, identity.Roles )
    {
    }
}

在您的 Global.asax 中:
    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.Identity is System.Web.Security.FormsIdentity)
        {

            HttpContext.Current.User = new CAA.Utility.Security.UserPrincipal(HttpContext.Current.User.Identity is CAA.Utility.Security.UserIdentity?  HttpContext.Current.User.Identity as CAA.Utility.Security.UserIdentity : new Utility.Security.UserIdentity(((System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity).Ticket));                


        }
    }

并写票:
                System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(1, user.Username, DateTime.Now, DateTime.Now.AddDays(1), false, String.Format("{0}|{1}|{2}", user.UserID ,user.Roles.ToString(), user.FirstName ), System.Web.Security.FormsAuthentication.FormsCookiePath);
                HttpCookie cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, System.Web.Security.FormsAuthentication.Encrypt(ticket));

                if (model.RememberMe)
                     cookie.Expires = ticket.Expiration;


                Response.Cookies.Add(cookie);

该代码可能难以理解,但逻辑是自定义“UserPrincipal”将自动解析 Forms Auth 票证的 UserData 部分,以获取您想要存储在那里的任何信息。在我的情况下,我存储名称、角色、id 等。在我的代码中,命名空间“CAA.Utility.Security”是存储我的自定义身份和主体的位置。

关于c# - ASP.NET MVC3 角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8978604/

相关文章:

c# - 为什么要断开与数据库的连接?

c# - 使用 ToList 的异步、等待和任务

asp.net - 即使在父级的 OnPreRender 期间附加控件时,控件的 OnInit 也会被调用吗?

asp.net-mvc - MVC3 编辑十进制字段和本地化

asp.net-mvc-3 - 如何在 ASP .NET MVC 3 中验证与另一个值相关的一个字段

c# - 不使用验证器验证日期?

c# - 包含返回一次性对象的方法的类是否需要实现 IDisposable?

c# - 如何实现推拉 Web 应用程序

javascript - 将图像异步加载到导航弹出窗口或加载图像的最佳方式

c# - 如何在使用 Razor 将文件上传到 MVC 3 中的 App_Data/Uploads 后查看文件?