【问题标题】:How to use new ASP.NET Identity 2.0 Roles and Authorize Attribute?如何使用新的 ASP.NET Identity 2.0 角色和授权属性?
【发布时间】:2014-06-08 15:45:05
【问题描述】:

我正在使用新的 ASP.NET Identity 2.0 系统。我知道我可以检查用户是否担任这样的角色:

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

我想这段代码可以写成在某些代码运行之前进行检查,但是 [Authorize] 属性呢?我曾经可以说:

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

这不再起作用,因为我不再使用旧的成员资格或角色管理。我怎样才能把两者放在一起?或者我如何防止应用程序的某些部分对正确角色的成员不可用?

Edit1:我不相信它有效。我将以下 Authorize 属性放在管理页面上,我能够以“客户帐户用户”的身份执行代码

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

另外,我想阻止未经授权的用户看到该页面。我们有代码来阻止菜单,但我仍然可以输入管理页面的 URL,并且未经授权的用户可以看到它

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

EDIT2:我们在 ASpNetRoles 表中手动创建了角色,并将用户映射到 ASPNetUsersToRoles 表中的角色。存在从用户到“客户服务管理员”等角色的映射。我们通过以下方式将用户添加到角色,但我认为它不起作用:

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

当普通用户登录时,他们不会通过在地址栏中输入进入管理页面的管理菜单:

http://localhost:53620/Admin/default

我该如何阻止它?

Edit3:我尝试按照您的示例 Eric 阻止所有用户访问管理页面,但我可以再次以客户用户身份登录,并且仍然在地址栏中键入上述内容并进入该页面。这有什么问题:

    <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:切换到 path="Admin/default.aspx" 会出现以下配置文件错误:

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

【问题讨论】:

  • 哎呀,这真是不升级的理由。如果不再有内置方法,我假设您可以编写自定义属性。
  • 您的假设是错误的。 Authorize 属性适用于 ASP.NET 标识。原因是 Authorize 属性不适用于 Membership 或 Identity,它适用于 IPrincipal 和 IIdentity,两者都与系统无关。您的问题很可能是因为您的姓名中有空格或未启用角色。
  • 该错误告诉您问题“此错误可能是由于虚拟目录未在 IIS 中配置为应用程序造成的”。在我看来,您在虚拟目录中有一个未配置为应用程序的 web.config。
  • 我的项目的 Account 文件夹中有一个 web.config,但我删除了它。我无法摆脱这个问题。我在这里遵循了 SO 帖子中的所有建议,但无济于事。我在 IIS Express 本地运行。
  • 我解决了这个问题。它与 SO 上的其他人不同。我在配置文件中有两个 区域。

标签: c# asp.net asp.net-identity


【解决方案1】:

我已经进行了几次测试,但无法重现您的问题。我使用了带空格和不带空格的角色,以及多个角色。一切都按预期进行。

你是如何添加角色的?这就是我的做法。

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

更新:

ASP.NET 具有三个主要组件.. WebForms、MVC 和 Web Pages。您正在使用 WebForms(不是经典的 asp.net 或任何其他术语)。

有几种方法可以按角色保护页面,但最简单的方法是在 web.config 中使用 location 元素来实现。再一次,这与它是 ASP.NET 身份或旧式角色或其他任何事实无关。基础 asp.net。例如,以下允许所有管理员访问该站点并拒绝所有其他用户,但允许 MyUsers 角色中的用户访问 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>

但是请注意,如果您使用路由,同一页面可能会被路由到两个不同的 url,这意味着它可以从一个 url 访问,但如果您不小心,则不能从另一个您的权限。

【讨论】:

  • 它们是通过放入表 ASpNetRoles 中手动创建的。我相信这就是 RoleManager 放置它们的地方。
  • 您需要做的还不止这些。您还必须映射 AspNetUserRoles 表
  • 哦,那个表也被映射了。它有一个用户条目及其在其中的角色。我们通过以下方式添加到角色,但如果 (manager.AddToRole(manager.FindByName(UserName.Text).Id, "Customer Account Admin").Succeeded) 似乎不起作用。我会把它放在Edit2中。 { c.logActivity("Register.aspx.cs", "REG_USER_ROLE", "将用户设置为管理员角色成功"); }
  • @user2471435 - 哦,我明白了...... Authorize 属性是 MVC 的一部分,它不被 WebForms 使用,这是您正在使用的。您可以在 web.config 位置元素中指定角色
  • 您能否展示一个使用 Identity 2 角色的代码示例?我知道这是愚蠢的经典 ASP.NET
【解决方案2】:

我也遇到了同样的问题。我想使用 AuthorizeAttribute 允许对管理员用户进行一些 Web api 调用。 [Authorize] 有效,但 [Authorize(Roles="Admin")] 无效。执行 [Authorize(Roles="Admin")] 的 API 调用很长,然后出现 SQL 异常(无法连接)。

我已将角色添加到角色管理器中。在我的数据表中,管理员角色与我的用户相关联。

有些奇怪:角色在声明中。

如果我这样做:

var claimIdentity = (ClaimsIdentity)HttpContext.Current.User.Identity;
var roleClaims = claimIdentity.Claims.Where(c => c.Type == ClaimTypes.Role);

我收到了一个带有“Admin”值的声明。我在 API 调用中使用它向管理员用户返回不同的结果,它工作正常。

另一个奇怪的事情是我尝试改用 User.IsInRole("Admin") 但它不起作用。所以我猜 AuthorizeAttribute 使用 IsInRole。

我将编写自己的 AuthorizeAttribute,使用声明检查,但我更喜欢使用本机解决方案。

克莱门特

【讨论】:

    【解决方案3】:

    在 Identity 3 中你可以使用这个:

    [Authorize(ClaimTypes.Role, "Administrator")]
    

    【讨论】:

      【解决方案4】:

      如果您在 Web.config 文件中启用了 roleManager,如下所示: &lt;roleManager enabled="true"/&gt; 你需要删除它。

      【讨论】:

      • 为我解决了这个问题!非常感谢(唯一评分为 0 的答案是工作的人)
      猜你喜欢
      • 2020-03-02
      • 1970-01-01
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 2011-10-24
      • 1970-01-01
      • 2021-02-27
      • 2013-12-03
      相关资源
      最近更新 更多