如何使用新的ASP.NET 2.0的身份角色和授权属性? [英] How to use new ASP.NET Identity 2.0 Roles and Authorize Attribute?

查看:182
本文介绍了如何使用新的ASP.NET 2.0的身份角色和授权属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在用新的ASP.NET身份2.0系统。我知道我可以检查,如果用户是在这样的角色:

 布尔isAdmin = UserManager.IsInRole(User.Identity.GetUserId()
   客户帐户管理);

我想这code可以写成某些code运行但什么[授权]属性前检查。我以前可以说:

  [授权(角色=客户帐户管理)]

由于我不使用旧的成员身份或角色管理了这不工作了。我怎样才能把两者结合起来?或者,我怎么防范不被提供给合适的角色?

成员的应用程序的某些部分

EDIT1:我不认为它的​​工作。我把下面的授权属性的管理页面上,我能够执行code作为一个客户帐户用户

  [授权(角色=客户服务管理,管理员Savitas)]
    公共部分类_default:System.Web.UI.Page

另外,我想从未经授权的用户看到阻止页面。我们有code挡住菜单,但我仍然可以键入URL到管理页面,它可以被未授权的​​用户可以看到

 如果(HttpContext.Current.User.IsInRole(客户帐户管理))
                    //
                    {
                    }
                    其他
                    {
                        MI = radmenu1.Items.FindItemByText(管理);
                        radmenu1.Items.Remove(MI);
                    }

EDIT2:我们在ASpNetRoles表手动创建角色并映射用户在ASPNetUsersToRoles表的作用。有一个从用户喜欢的角色映射客户服务管理。我们将用户添加到角色具有以下,但我不相信它的工作原理:

 如果(manager.AddToRole(manager.FindByName(UserName.Text).ID,客户帐户管理)。成功)
                                {
                                    c.logActivity(Register.aspx.cs,REG_USER_ROLE,设置用户管理员角色成功);
                                }

当他们中的一个普通用户登录不通过输入到地址栏获得管理菜单管理页面:

 的http://本地主机:53620 /行政/默认

如何停止?

EDIT3:我试图阻止所有用户按您的例子埃里克·管理页面,但再一次,我可以作为一个客户用户登录并输入还是上面的地址栏中,并获得了页面。有什么不对的:

 <结构>
  < configSections>    <节名称=的EntityFrameworkTYPE =System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,的EntityFramework,版本6.0.0.0 =文化=中性公钥= b77a5c561934e089requirePermission =FALSE/>
  <! - 有关Entity Framework的配置的详细信息,请访问http://go.microsoft.com/fwlink/?LinkID=237468 - >< / configSections>
  <&是connectionStrings GT;
    ...
  < /&是connectionStrings GT;
  <位置路径=〜/行政/ Default.aspx的>
    <&的System.Web GT;
      <授权>
        <让角色=客户服务管理/>
        <拒绝用户=*/>
      < /授权>

Edit4:切换到路径=管理/ Default.aspx的提供了以下配置文件错误:

 配置错误
  说明:该请求提供服务所需的配置文件的处理过程中发生错误。请检查下面的特定错误详细信息并适当地修改配置文件。 分析器错误信息:这是使用注册为allowDefinition =应用程序级别之外'MachineToApplication'的节是错误的。这个错误可以通过未被配置为在IIS中应用程序的虚拟目录引起的。源错误:66号线:LT; /控制>
第67行:LT; /页>
68号线:其中,会员>
69号线:其中,供应商>
70号线:< - ASP.NET成员在此模板禁用。请访问以下链接http://go.microsoft.com/fwlink/?LinkId=301889了解此模板ASP.NET成员支持


解决方案

我已经进行多次试验,我一直无法重现你的问题。我用的角色有和没有空间,多个角色。一切都按预期工作。

你是如何加入的角色?以下是我正在做的。

  VAR roleManager =新RoleManager< IdentityRole>(新Rolestore的< IdentityRole>());
roleManager.Create(新IdentityRole(这是一个测试));
UserManager.AddToRole(user.Id,这是一个测试);

更新:

ASP.NET三大部分组成..的WebForms,MVC,和网页。您正在使用的WebForms(不是经典的asp.net或任何其他条款)。

有几种方法按角色,以确保一个页面,但最简单的是做它用一个位置元素的Web.config。再次,这具有的没有的任何与它是ASP.NET身份或老式的角色或任何...这一切工作了通用的IPrincipal和IIdentity的接口其实这样做是部分基地asp.net。例如,下面让所有管理员接取该网站,并拒绝所有其他用户,但允许在MyUsers角色的用户访问CoolStuff.aspx:

 <结构>
 <&的System.Web GT;
      <授权>
           <让角色=管理员/>
           <拒绝用户=*/>
      < /授权> < /system.web> <! - 允许所有MyUsers角色的用户访问CoolStuff.aspx - >
 <位置路径=CoolStuff.aspx>
      <&的System.Web GT;
           <授权>
                <让角色=MyUsers/>
           < /授权>
      < /system.web>
 < /地点>
< /结构>

但请注意,如果你使用的路由,这是可能的,同样的页面可以被路由到两个不同的网址,这意味着它可以访问从一个网址,而不是其他,如果你不小心您的权限。

I am using the new ASP.NET Identity 2.0 system. I know I can check if a user is in a role like this:

bool isAdmin = UserManager.IsInRole(User.Identity.GetUserId(), 
   "Customer Account Admin");

I guess this code can be written to check before certain code is run but what about the [Authorize] attribute. I used to be able say:

[Authorize(Role="Customer Account Admin")]

This doesn't work anymore because I am not using the old membership or Role Management anymore. How can I put the two together? Or how do I guard against certain parts of the application not being available to members of the right role?

Edit1: I don't believe that it's working. I put the following Authorize attribute on an Admin page and I am able to execute the code as a "Customer Account User"

   [Authorize(Roles = "Customer Service Admin, Savitas Admin")]
    public partial class _default : System.Web.UI.Page

Also, I would like to block that page from being seen by unauthorized users. We have code to block the menu but I can still type the URL to the Admin page and it can be seen by unauthorized users

 if (HttpContext.Current.User.IsInRole("Customer Account Admin"))
                    //
                    {
                    }
                    else
                    {
                        mi = radmenu1.Items.FindItemByText("Admin");
                        radmenu1.Items.Remove(mi);
                    }

EDIT2: We created the roles manually in the ASpNetRoles table and mapped users to roles in the ASPNetUsersToRoles table. There is a mapping from users to roles like "Customer Service Admin." We add users to roles with the following but I don't believe it works:

if (manager.AddToRole(manager.FindByName(UserName.Text).Id, "Customer Account Admin").Succeeded)
                                {
                                    c.logActivity("Register.aspx.cs", "REG_USER_ROLE", "Setting user to Admin role succeeded");
                                }

When a regular user logs in they don't get an Admin menu to the Admin page by typing into the address bar:

http://localhost:53620/Admin/default

How do I stop that?

Edit3: I tried to block all users to the Admin page per your example Eric but once again, I can log in as a Customer User and still type the above in the address bar and get to the page. What's wrong with this:

    <configuration>
  <configSections>

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
  <connectionStrings>
    ...
  </connectionStrings>
  <location path="~/Admin/default.aspx">
    <system.web>
      <authorization>
        <allow roles="Customer Service Admin" />
        <deny users="*"/>
      </authorization>

Edit4: Switching to path="Admin/default.aspx" gives the following config file error:

Configuration Error 
  Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. 

 Parser Error Message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.

Source Error: 



Line 66:         </controls>
Line 67:       </pages>
Line 68:       <membership>
Line 69:         <providers>
Line 70:           <!--        ASP.NET Membership is disabled in this template. Please visit the following link http://go.microsoft.com/fwlink/?LinkId=301889 to learn about the ASP.NET Membership support in this template

解决方案

I've performed several tests and I have not been able to recreate your problem. I've used roles with and without spaces, and multiple roles. And everything works as expected.

How are you adding the roles? Here's how I'm doing it.

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>());
roleManager.Create(new IdentityRole("This Is A Test"));
UserManager.AddToRole(user.Id, "This Is A Test");

UPDATE:

ASP.NET has three major components.. WebForms, MVC, and Web Pages. You're using WebForms (not classic asp.net or any other term).

There are several ways to secure a page by role, but the easiest is to do it in the web.config using a location element. Once again, this has nothing whatsoever to do with the fact of it being ASP.NET Identity or old style roles or whatever... it all works off the generic IPrincipal and IIdentity interfaces that are part of the base asp.net. For instance the following allows all administrators to acess the site and denies all other users, but allows users in the MyUsers role to access CoolStuff.aspx:

<configuration>    
 <system.web>    
      <authorization>    
           <allow roles="Administrators" />    
           <deny users="*"/>    
      </authorization>    

 </system.web>

 <!-- Allow all "MyUsers" role users to access CoolStuff.aspx -->    
 <location path="CoolStuff.aspx">    
      <system.web>    
           <authorization>    
                <allow roles="MyUsers" />    
           </authorization>    
      </system.web>    
 </location>    
</configuration>

Please be aware however, if you're using routing, it's possible that that the same page can be routed to two different url's, which means that it could be accessible from one url, but not another if you are not careful with your permissions.

这篇关于如何使用新的ASP.NET 2.0的身份角色和授权属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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