简体   繁体   English

在ASP.NET标识中添加角色

[英]Add role in ASP.NET Identity

How can I add a Role in the new ASP.NET Identity system (1.0)? 如何在新的ASP.NET身份系统(1.0)中添加角色? There is a UserStore class but no RoleStore class. 有一个UserStore类但没有RoleStore类。

I can't find any documentation on this issue. 我找不到关于这个问题的任何文件。

RoleManager = new RoleManager<IdentityRole>(
                  new RoleStore<IdentityRole>(new MyDbContext()));
var roleresult = RoleManager.Create(new IdentityRole(roleName));

Starting with the .NET Framework 4.5, Windows Identity Foundation (WIF) has been fully integrated into the .NET Framework. 从.NET Framework 4.5开始,Windows Identity Foundation(WIF)已完全集成到.NET Framework中。

I would advice to examine the possibility, in my opinion the preferred, to implement Authorization through Claims ( Expressing Roles as Claims ). 我建议检查在我看来是首选的,通过索赔实施授权( 表达角色作为索赔 )的可能性。

When the IsInRole() method is called, there is a check made to see if the current user has that role. 调用IsInRole()方法时,会检查当前用户是否具有该角色。 In claims-aware applications, the role is expressed by a role claim type that should be available in the token. 在声明感知应用程序中,角色由应在令牌中提供的角色声明类型表示。

The role claim type is expressed using the following URI: " http://schemas.microsoft.com/ws/2008/06/identity/claims/role " 角色声明类型使用以下URI表示:“ http://schemas.microsoft.com/ws/2008/06/identity/claims/role

So from the UserManager you can do something like this (without the RoleManager): 所以从UserManager你可以做这样的事情(没有RoleManager):

var um = new UserManager();
um.AddClaimAsync(1, new Claim(ClaimTypes.Role, "administrator"));

Claims can simplify and increase the performance of authentication and authorization processes. 声明可以简化并提高身份验证和授权过程的性能。 You can use the roles stored as claims to eliminate back-end queries every time authorization takes place. 您可以使用存储为声明的角色在每次授权时消除后端查询。

Using Claims you will not need the RoleStore anymore (at least for the equivalent authorization purposes...) 使用声明您将不再需要RoleStore(至少为了等效的授权目的......)

I used below snippets in one sample asp.net web page page_load for starting to grasp the way ASP Identity works 我在一个示例asp.net网页page_load中使用了以下代码片段来开始掌握ASP Identity的工作方式

   UserManager userManager = new UserManager();
    var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
    var roleManager = new RoleManager<IdentityRole>(roleStore);
    var applicationRoleAdministrator = new IdentityRole("superadmin");
    if (!roleManager.RoleExists(applicationRoleAdministrator.Name))
    {
        roleManager.Create(applicationRoleAdministrator);
    }
     ApplicationUser applicationUserAdministrator = userManager.FindByName(User.Identity.Name);

    if (!userManager.GetRoles(applicationUserAdministrator.Id).Contains("superadmin"))
    {
        Response.Redirect("~/account/login.aspx?ReturnUrl=" + Request.Url.AbsolutePath);
    }

Of course below ApplicationDbContext is automatically generated with ASP.NET 4.5+ templates like below 当然,ApplicationDbContext下面是使用ASP.NET 4.5+模板自动生成的,如下所示

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }

Also Create application Role Manager class too 还要创建应用程序Role Manager类

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
        : base(roleStore)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        //return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
        return new ApplicationRoleManager(new RoleStore<IdentityRole>(new ApplicationDbContext()));
    }
}

also add below line in your startup.Auth.cs => ConfigureAuth(IAppBuilder app) method 在startup.Auth.cs => ConfigureAuth(IAppBuilder app)方法中添加以下行

  app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

And then in your controller: 然后在你的控制器中:

private ApplicationRoleManager _roleManager;

public ApplicationRoleManager RoleManager
{
    get
    {
        return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
    }
    private set
    {
        _roleManager = value;
    }
}

I am new to this Identity Stuff and I am not sure if it is necessary or I am doing it clean and right, but these steps worked for me 我是这个Identity Stuff的新手,我不确定是否有必要,或者我干净利落,但这些步骤对我有用

ASP.NET identity is claims aware with respect to roles. ASP.NET身份是关于角色的声明。 That really confused me because in the previous system you configured membership and role providers in web.config. 这让我很困惑,因为在之前的系统中,您在web.config中配置了成员资格和角色提供程序。

The issue for me is that I have code like this: 对我来说问题是我有这样的代码:

HttpContext.Current.User.IsInRole("some role")

Fortunately, this logic still works. 幸运的是,这种逻辑仍然有效。 You can see the logic in the CreateAsync function in ClaimsIdentityFactory.cs which is in Microsoft.AspNet.Identity.Core . 您可以在Microsoft.AspNet.Identity.Core中的CreateAsync看到CreateAsync函数中的逻辑。 One of the arguments is UserManager . 其中一个参数是UserManager It asks it if it SupportsUserRole and if so then it calls GetRolesAsync and adds each role as a claim to the ClaimIdentity . 它询问它是否为SupportsUserRole ,如果是,则调用GetRolesAsync并将每个角色作为声明添加到ClaimIdentity There is no need to do this yourself. 没有必要自己这样做。

IsInRole uses claims as described here: IsInRole使用如下所述的声明:

http://msdn.microsoft.com/en-us/library/hh545448.aspx http://msdn.microsoft.com/en-us/library/hh545448.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM