2010-05-01 83 views
2

我正在使用带有自定义身份验证机制的窗体身份验证的ASP.NET网站(以编程方式在protected void Login_Authenticate(object sender, AuthenticateEventArgs e)上设置e.Authenticated)。ASP.NET中的自定义角色

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

我想避免什么:

  • 设置自定义角色提供:太多的代码编写这样一个基本的东西,
  • 改造现有的代码,例如通过移除网站地图,并通过替换它一个代码隐藏解决方案。

我想要做什么:

  • 一个纯粹的代码隐藏解决方案,这将让我分配上进行身份验证事件的作用。

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

回答

4

正如马修所说,建立一个委托人并在恰当的时机设置它是利用所有基于角色的好东西(如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 
} 
2

我用这个技术,它Microsoft建议:

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

在全球ASAX我拦截权威性的cookie,然后设置线程原理和HttpContext的用户和同一角色。在你可以使用HttpContext.Current.User.IsInRole(“foo”)之后,你可以在WinForm equivallent中使用这种类型的代码。

您越是可以依赖内置模式,安全模式越可能会越安全,维护开发人员越可能识别如何使用模式。

相关问题