ASP.NET中的自定义角色 [英] Custom roles in ASP.NET

查看:173
本文介绍了ASP.NET中的自定义角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个ASP.NET网站,该网站使用窗体身份验证使用自定义的验证机制(它设置在 e.Authenticated 编程上保护无效Login_Authenticate(对象发件人,AuthenticateEventArgs E))。

I am working on an ASP.NET website which uses forms authentication with a custom authentication mechanism (which sets e.Authenticated programmatically on protected void Login_Authenticate(object sender, AuthenticateEventArgs e)).

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

I have an ASP.NET sitemap. Some elements must be displayed only to logged in users. Others must be displayed only to one, unique user (ie. administrator, identified by a user name which will never change).

我想避免什么:


  • 设置自定义角色提供:太多了code为这样一个基本的东西写,

  • 通过删除网站地图,并以$ C $替换它的c-背后的解决方案改造现有code为例。

我想要做的:


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

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

Is it possible? How? If not, is there an easy-to-do workaround?

推荐答案

至于马太说,建设主体,并在适当的时候自己设定它采取一切内置的基于角色的好东西像网站地图的优势,最简单的方法

As Matthew says, building a principal and setting it yourself at the right moment is the easiest way to take advantage of all of the built in Role based goodies like SiteMap.

但是,实施这一比MSDN所示的要容易得多基于标准的方法。

But there is a much easier standards based method of implementing this than shown by MSDN.

这是我如何实现一个简单的角色提供

This is how I implement a simple role provider

Global.asax中

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));
            }
        }
    }
}

要手动检查用户在一个页面codebehind的背景:

To manually check the user in the context of a Page codebehind:

if (User.IsInRole("admins"))
{
  // allow something
}

在其他地方刚刚得到的用户从当前上下文的

Elsewhere just get the user off of the current context

if (HttpContext.Current.User.IsInRole("admins"))
{
  // allow something
}

这篇关于ASP.NET中的自定义角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆