c# - ASP.NET 中的自定义角色

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

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

我有一个 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
}

关于c# - ASP.NET 中的自定义角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2750215/

相关文章:

c# - 没有源代码的 ASP.NET 扩展应用程序

c# - 在 TransactionScope 中登记 System.Web.Providers

asp.net - 我的 Membership ValidateUser 请求有什么问题? (使用 ClientFormsAuthenticationMembershipProvider)

c# - 数组作为字典键会产生很多冲突

c# - 使用 NHibernate 映射时覆盖列大小写

c# - 是否有将 ANSI C 代码转换为 C# 的工具?

c# - 将某人从 Web 应用程序注销的最佳方法是什么?

javascript - 验证尺寸文本输入 javascript

c# - 在 asp.net c# 中选择开始和结束日期后,在另一个文本框中自动生成天数

asp.net-membership - 如何在成员(member)中获取用户 ID?