ASP.NET中的自定义角色

时间:2010-05-01 14:02:44

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

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

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

我想避免的事情:

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

我想做什么:

  • 一个纯代码隐藏解决方案,它允许我在身份验证事件上分配角色。

有可能吗?怎么样?如果没有,是否有一个易于使用的解决方法?

2 个答案:

答案 0 :(得分:4)

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

但是实现这一点的方法要比MSDN显示的更容易。

这是我实现简单角色提供程序的方式

Global.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
}

答案 1 :(得分:2)

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

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

在全局asax中,我拦截了auth cookie,然后设置了线程原则和HttpContext用户以及相同的角色。在你可以使用HttpContext.Current.User.IsInRole(“foo”)之后,你将在WinForm等效中使用相同类型的代码。

您越依赖内置模式,安全性越高,维护开发人员越有可能认识到如何使用模式。

相关问题