[英]Add User to Role ASP.NET Identity
我知道新成員包括一個“簡單角色提供者”。
在創建用戶時,我找不到與創建用戶和分配角色有關的任何幫助。 我添加了一個可以在數據庫上正確創建表的用戶。 我看到了AspNetRoles
, AspNetUserRoles
和AspNetUsers
表。
我想從一個角色分配AspNetRoles
在用戶AspNetUsers
該角色/用戶兩者的ID將被存儲在AspNetUserRoles。
在創建用戶時,我在程序設計部分中會限制在何處以及如何執行此操作。
我有一個下拉列表來選擇角色,但是使用實體CF和新的ASP.NET身份模型時,我不確定如何從下拉列表中選擇selectedvalue的ID和UserID並分配角色。
我在這里找到了很好的答案在新的VS 2013 Identity UserManager中動態添加角色
但是為了提供一個示例,以便您可以檢查它,我將共享一些默認代碼。
首先,請確保您已插入角色。
然后對用戶注冊方法進行測試。
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var currentUser = UserManager.FindByName(user.UserName);
var roleresult = UserManager.AddToRole(currentUser.Id, "Superusers");
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
最后,您必須以某種方式從“角色”下拉列表中獲得“超級用戶”。
我也面臨同樣的挑戰。 這是我發現的將用戶添加到角色的解決方案。
internal class Security
{
ApplicationDbContext context = new ApplicationDbContext();
internal void AddUserToRole(string userName, string roleName)
{
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
try
{
var user = UserManager.FindByName(userName);
UserManager.AddToRole(user.Id, roleName);
context.SaveChanges();
}
catch
{
throw;
}
}
}
當我同意有關RoleManager的其他答案時,我建議檢查通過聲明(將角色表示為聲明 )實現授權的可能性。
從.NET Framework 4.5開始,Windows Identity Foundation(WIF)已完全集成到.NET Framework中。
在聲明感知應用程序中,角色由應在令牌中可用的角色聲明類型表示。 調用IsInRole()方法時,將進行檢查以查看當前用戶是否具有該角色。
角色聲明類型使用以下URI表示:“ http://schemas.microsoft.com/ws/2008/06/identity/claims/role ”
因此,除了使用RoleManager之外 ,您還可以從UserManager中 “將用戶添加到角色”,如下所示:
var um = new UserManager();
um.AddClaimAsync(1, new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "administrator"));
通過以上幾行,您已向ID為“ 1”的用戶添加了一個值為“ administrator”的角色聲明...
根據MSFT的建議,聲明授權可以簡化並提高身份驗證和授權過程的性能,從而消除每次進行授權時都會進行的某些后端查詢。
使用聲明,您可能不再需要RoleStore。 (AspNetRoles,AspNetUserRoles)
您是否正在尋找這樣的東西:
RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new MyDbContext()));
var str = RoleManager.Create(new IdentityRole(roleName));
同時檢查用戶身份
檢查此鏈接: 為用戶分配角色 。 您可以在CreateUserWIzard控件中添加一個步驟,然后在該步驟中選擇角色。
<asp:CreateUserWizard ID="RegisterUserWithRoles" runat="server"
ContinueDestinationPageUrl="~/Default.aspx" LoginCreatedUser="False"
onactivestepchanged="RegisterUserWithRoles_ActiveStepChanged">
<WizardSteps>
<asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">
</asp:CreateUserWizardStep>
<asp:WizardStep ID="SpecifyRolesStep" runat="server" AllowReturn="False"
StepType="Step" Title="Specify Roles">
<h3>Choose the role.</h3>
<asp:CheckBoxList ID="RoleList" runat="server">
</asp:CheckBoxList>
</asp:WizardStep>
<asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">
</asp:CompleteWizardStep>
</WizardSteps>
</asp:CreateUserWizard>
在后面的代碼中,您將擁有:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Reference the SpecifyRolesStep WizardStep
WizardStep SpecifyRolesStep = RegisterUserWithRoles.FindControl("SpecifyRolesStep") as WizardStep;
// Reference the RoleList CheckBoxList
CheckBoxList RoleList = SpecifyRolesStep.FindControl("RoleList") as CheckBoxList;
// Bind the set of roles to RoleList
RoleList.DataSource = Roles.GetAllRoles();
RoleList.DataBind();
}
}
protected void RegisterUserWithRoles_ActiveStepChanged(object sender, EventArgs e)
{
// Have we JUST reached the Complete step?
if (RegisterUserWithRoles.ActiveStep.Title == "Complete")
{
// Reference the SpecifyRolesStep WizardStep
WizardStep SpecifyRolesStep = RegisterUserWithRoles.FindControl("SpecifyRolesStep") as WizardStep;
// Reference the RoleList CheckBoxList
CheckBoxList RoleList = SpecifyRolesStep.FindControl("RoleList") as CheckBoxList;
// Add the checked roles to the just-added user
foreach (ListItem li in RoleList.Items)
{
if (li.Selected)
Roles.AddUserToRole(RegisterUserWithRoles.UserName, li.Text);
}
}
}
以下是使用基於Claims的角色的“創建用戶”控制器方法的替代實現。
然后,創建的聲明將使用Authorize屬性,例如[Authorize(Roles =“ Admin,User。*,User.Create”)]
// POST api/User/Create
[Route("Create")]
public async Task<IHttpActionResult> Create([FromBody]CreateUserModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Generate long password for the user
var password = System.Web.Security.Membership.GeneratePassword(25, 5);
// Create the user
var user = new ApiUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
// Add roles (permissions) for the user
foreach (var perm in model.Permissions)
{
await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, perm));
}
return Ok<object>(new { UserName = user.UserName, Password = password });
}
這對我有用。 您可以在AccountController-> Register上看到此代碼
var user = new JobUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
//add this to add role to user
await UserManager.AddToRoleAsync(user.Id, "Name of your role");
}
但是角色名稱必須存在於您的AspNetRoles表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.