[英]Add role in ASP.NET Identity
如何在新的ASP.NET身份系統(1.0)中添加角色? 有一個UserStore
類但沒有RoleStore
類。
我找不到關於這個問題的任何文件。
RoleManager = new RoleManager<IdentityRole>(
new RoleStore<IdentityRole>(new MyDbContext()));
var roleresult = RoleManager.Create(new IdentityRole(roleName));
從.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的新手,我不確定是否有必要,或者我干凈利落,但這些步驟對我有用
ASP.NET身份是關於角色的聲明。 這讓我很困惑,因為在之前的系統中,您在web.config中配置了成員資格和角色提供程序。
對我來說問題是我有這樣的代碼:
HttpContext.Current.User.IsInRole("some role")
幸運的是,這種邏輯仍然有效。 您可以在Microsoft.AspNet.Identity.Core
中的CreateAsync
看到CreateAsync
函數中的邏輯。 其中一個參數是UserManager
。 它詢問它是否為SupportsUserRole
,如果是,則調用GetRolesAsync
並將每個角色作為聲明添加到ClaimIdentity
。 沒有必要自己這樣做。
IsInRole
使用如下所述的聲明:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.