将用户添加到角色ASP.NET标识

时间:2013-10-30 16:58:51

标签: asp.net asp.net-identity asp.net-roles

我知道新会员资格包括“简单角色提供者”。

在创建用户时,我找不到与创建用户和分配角色相关的任何帮助。我添加了一个用户,可以正确地在数据库上创建表格。我看到了AspNetRolesAspNetUserRolesAspNetUsers表。

我希望将AspNetRoles中的角色分配给AspNetUsers中的用户,其中角色/用户的 ID 将存储在AspNetUserRoles中。

当我创建用户时,我会停留在编程部分,在哪里以及如何执行此操作。

我有一个下拉列表来选择角色,但是使用Entity CF和新的ASP.NET Identity模型我不知道如何从下拉列表中获取selectedvalue的ID和UserID并分配角色

7 个答案:

答案 0 :(得分:61)

我在这里找到了很好的答案Adding Role dynamically in new VS 2013 Identity UserManager

但是为了提供一个示例,以便您可以检查它,我将分享一些默认代码。

首先确保已插入角色。

enter image description here

然后在用户注册方法上进行第二次测试。

[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);
}

最后你必须以某种方式从角色下拉列表中获得“超级用户”。

答案 1 :(得分:23)

我遇到了同样的挑战。这是我发现将用户添加到角色的解决方案。

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;
        }
    }
}

答案 2 :(得分:10)

虽然我同意有关RoleManager的其他答案,但我建议检查通过声明实施授权的可能性(Expressing Roles as Claims)。

从.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"));

通过上述行,您已向用户添加了值为“administrator”的角色声明,其ID为“1”...

根据MSFT的建议,声明授权可以简化并提高身份验证和授权流程的性能,从而在每次授权时都会消除一些后端查询。

使用声明您可能不再需要RoleStore。 (AspNetRoles,AspNetUserRoles)

答案 3 :(得分:8)

你在寻找这样的东西:

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

同时检查User Identity

答案 4 :(得分:2)

点击此链接:Assigning Roles to Users。您可以向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);
        }
    }
}

答案 5 :(得分:2)

以下是“创建用户”的另一种实现方式。控制器方法使用基于声明的角色

创建的声明然后使用Authorize属性,例如[授权(Roles =&#34; Admin,User。*,User.Create&#34;)]

    // 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 });
    }

答案 6 :(得分:0)

这个对我有用。您可以在AccountController上查看此代码->注册

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表中。

相关问题