I know the new Membership includes a \"Simple Role Provider.\"
I can\'t find any help related to creating a user and assigning a role when the user is created. I\'v
Check this link: Assigning Roles to Users. You can add a step to your CreateUserWIzard control and choose the roles in that step.
<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>
And in the code-behind you will have:
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);
}
}
}
I found good answer here Adding Role dynamically in new VS 2013 Identity UserManager
But in case to provide an example so you can check it I am gonna share some default code.
First make sure you have Roles inserted.
And second test it on user register method.
[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);
}
And finally you have to get "Superusers" from the Roles Dropdown List somehow.
Are you looking for something like this:
RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new MyDbContext()));
var str = RoleManager.Create(new IdentityRole(roleName));
Also check User Identity
While I agree with the other answers regarding the RoleManager, I would advice to examine the possibility to implement Authorization through Claims (Expressing Roles as Claims).
Starting with the .NET Framework 4.5, Windows Identity Foundation (WIF) has been fully integrated into the .NET Framework.
In claims-aware applications, the role is expressed by a role claim type that should be available in the token. When the IsInRole() method is called, there is a check made to see if the current user has that role.
The role claim type is expressed using the following URI: "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
So instead of using the RoleManager, you can "add a user to a role" from the UserManager, doing something like this:
var um = new UserManager();
um.AddClaimAsync(1, new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "administrator"));
With the above lines you have added a role claim with the value "administrator" to the user with the id "1"...
Claims authorization, as suggested by MSFT, can simplify and increase the performance of authentication and authorization processes eliminating some back-end queries every time authorization takes place.
Using Claims you may not need the RoleStore anymore. (AspNetRoles, AspNetUserRoles)
This one works for me. You can see this code on 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");
}
but the role name must exist in your AspNetRoles table.
I had the same challenge. This is the solution I found to add users to roles.
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;
}
}
}