dan*_*iel 40 asp.net asp.net-identity
如何在新的ASP.NET身份系统(1.0)中添加角色?有一个UserStore班级,但没有RoleStore班级.
我找不到关于这个问题的任何文件.
gra*_*row 43
RoleManager = new RoleManager<IdentityRole>(
                  new RoleStore<IdentityRole>(new MyDbContext()));
var roleresult = RoleManager.Create(new IdentityRole(roleName));
MyO*_*Way 36
从.NET Framework 4.5开始,Windows Identity Foundation(WIF)已完全集成到.NET Framework中.
我建议检查在我看来是首选的,通过索赔实施授权(表达角色作为索赔)的可能性.
调用IsInRole()方法时,会检查当前用户是否具有该角色.在声明感知应用程序中,角色由应在令牌中提供的角色声明类型表示.
角色声明类型使用以下URI表示:" http://schemas.microsoft.com/ws/2008/06/identity/claims/role "
所以从UserManager你可以做这样的事情(没有RoleManager):
var um = new UserManager();
um.AddClaimAsync(1, new Claim(ClaimTypes.Role, "administrator"));
声明可以简化并提高身份验证和授权过程的性能.您可以使用存储为声明的角色在每次授权时消除后端查询.
使用声明您将不再需要RoleStore(至少为了等效的授权目的......)
我在一个示例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);
    }
当然,ApplicationDbContext下面是使用ASP.NET 4.5+模板自动生成的,如下所示
 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }
还要创建应用程序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()));
    }
}
在startup.Auth.cs => ConfigureAuth(IAppBuilder app)方法中添加以下行
  app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
然后在你的控制器中:
private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
    get
    {
        return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
    }
    private set
    {
        _roleManager = value;
    }
}
我是这个Identity Stuff的新手,我不确定是否有必要,或者我干净利落,但这些步骤对我有用
| 归档时间: | 
 | 
| 查看次数: | 54150 次 | 
| 最近记录: |