代码之家  ›  专栏  ›  技术社区  ›  Arseni Mourzenko

ASP.NET中的自定义角色

  •  2
  • Arseni Mourzenko  · 技术社区  · 16 年前

    我正在一个ASP.NET网站上工作,该网站使用带有自定义身份验证机制的表单身份验证(设置 e.Authenticated 以编程方式打开 protected void Login_Authenticate(object sender, AuthenticateEventArgs e) )

    我有一个ASP.NET站点地图。某些元素只能显示给登录的用户。其他用户只能显示给一个唯一的用户(即管理员,由永不更改的用户名标识)。

    我想避免的是:

    • 设置一个自定义角色提供程序:对于这样一个基本的东西来说,写太多的代码,
    • 转换现有代码,例如删除站点地图并用代码隐藏解决方案替换它。

    我想做的是:

    • 纯代码隐藏解决方案,允许我在authenticate事件上分配角色。

    有可能吗?怎样?如果没有,是否有一个简单的解决方法?

    2 回复  |  直到 16 年前
        1
  •  4
  •   Sky Sanders    16 年前

    正如Matthew所说,构建一个主体并在适当的时候自己设置它是利用所有内置的基于角色的好东西(如Sitemap)的最简单的方法。

    但是有一种比msdn显示的更容易实现这一点的基于标准的方法。

    这就是我如何实现一个简单的角色提供程序

    阿萨克斯全球公司

    using System;
    using System.Collections.Specialized;
    using System.Security.Principal;
    using System.Threading;
    using System.Web;
    using System.Web.Security;
    
    namespace SimpleRoles
    {
        public class Global : HttpApplication
        {
            private static readonly NameValueCollection Roles =
                new NameValueCollection(StringComparer.InvariantCultureIgnoreCase)
                    {
                        {"administrator", "admins"},
                        // note, a user can be in more than one role
                        {"administrator", "codePoets"},
                    };
    
            protected void Application_AuthenticateRequest(object sender, EventArgs e)
            {
                HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie != null)
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
                    Context.User = Thread.CurrentPrincipal =
                                   new GenericPrincipal(Context.User.Identity, Roles.GetValues(ticket.Name));
                }
            }
        }
    }
    

    要在页面代码隐藏的上下文中手动检查用户,请执行以下操作:

    if (User.IsInRole("admins"))
    {
      // allow something
    }
    

    在其他地方,只需让用户离开当前上下文

    if (HttpContext.Current.User.IsInRole("admins"))
    {
      // allow something
    }
    
        2
  •  2
  •   MatthewMartin muthu    16 年前

    我使用微软推荐的这种技术:

    http://msdn.microsoft.com/en-us/library/aa302399.aspx

    在全局asax中,我截取auth cookie,然后设置线程原则和httpContext用户以及它们的角色。在您可以使用httpcontext.current.user.isinRole(“foo”)之后,这与您将在WinFormEquivalent中使用的代码类型大致相同。

    您越能依赖内置模式,它就越有可能是安全的,维护开发人员就越能识别如何使用该模式。

    推荐文章