我正在开发一个 ASP.NET 网站,该网站使用带有自定义身份验证机制的表单身份验证(该机制设置e.Authenticated
以编程方式protected void Login_Authenticate(object sender, AuthenticateEventArgs e)
).
我有一个 ASP.NET 站点地图。某些元素必须仅向登录用户显示。其他的必须仅显示给一个唯一的用户(即管理员,由永不更改的用户名标识)。
我想避免的:
- 设置自定义角色提供程序:为这样的基本事情编写太多代码,
- 改造现有代码,例如删除站点地图并将其替换为代码隐藏解决方案。
我想做的事:
- 一个纯粹的代码隐藏解决方案,它允许我在身份验证事件上分配角色。
是否可以?如何?如果没有,有没有简单易行的解决方法?
正如 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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)