【问题标题】:Custom roles in ASP.NETASP.NET 中的自定义角色
【发布时间】:2010-05-01 14:02:43
【问题描述】:

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

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

我想避免的:

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

我想做什么:

  • 一个纯代码隐藏解决方案,可让我在身份验证事件中分配角色。

有可能吗?如何?如果没有,是否有简单的解决方法?

【问题讨论】:

    标签: c# asp.net asp.net-membership asp.net-roles


    【解决方案1】:

    正如 Matthew 所说,构建主体并在适当的时候自行设置是利用所有内置角色(如 SiteMap)的最简单方法。

    但是有一个比 MSDN 显示的更简单的基于标准的实现方法。

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

    全球.asax

    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】:

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

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

      在全局asax中我截取了auth cookie,然后设置线程原理和HttpContext用户和角色一样。在您可以使用 HttpContext.Current.User.IsInRole("foo") 之后,这与您在 WinForm 等效项中使用的代码非常相似。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-13
        • 2015-07-16
        • 2021-02-02
        • 1970-01-01
        • 1970-01-01
        • 2015-07-21
        • 1970-01-01
        • 2023-03-12
        相关资源
        最近更新 更多