【问题标题】: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
}