我正在使用新的ASP.NET Identity 2.0系统。我知道我可以检查一个用户是否在这样的角色:
bool isAdmin = UserManager.IsInRole(User.Identity.GetUserId(),
"Customer Account Admin");
我想这个代码可以在运行某些代码之前编写以检查,但是[Authorize]属性呢。我曾经说过:
[Authorize(Role="Customer Account Admin")]
这不再起作用,因为我不再使用旧的成员资格或角色管理。我怎么把两者放在一起?或者我如何防范应用程序的某些部分无法提供给正确角色的成员?
编辑1:我不相信它有效。我在管理页面上放置了以下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
我怎么阻止它?
编辑3:我试图按照你的示例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