ASP.NET中的自定义角色

 2023-02-16    407  

问题描述

我正在研究一个ASP.NET网站,它使用Forms身份验证具有自定义身份验证机制(以编程方式在protected void Login_Authenticate(object sender, AuthenticateEventArgs e)上编程设置e.Authenticated).

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

ASP.NET中的自定义角色

我想要避免的内容:

  • 设置了自定义角色提供程序:太多代码来写入这样的基本件,
  • 转换现有代码,例如通过删除站点地图并通过代码解决方案替换它.

我想做什么:

  • 一个纯代码解决方案,它将让我在身份验证事件上分配角色.

是可能的吗?如何?如果没有,是否有一个易于解决的解决方法?

推荐答案

随着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
}

其他推荐答案

我使用Microsoft推荐的技术:

在全局asax中,我拦截Auth cookie,然后设置线程原理和HttpContext用户以及相同的角色.可以使用httpcontext.current.user.isinrole(“foo”),这与您将在WinForm Equivallent中使用的相同类型的代码.

您可以依赖于图案的内置模式,所需的可能性越可能,维护开发人员的可能性就越有可能识别如何使用模式.

以上所述是小编给大家介绍的ASP.NET中的自定义角色,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!

原文链接:https://77isp.com/post/34012.html

=========================================

https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。