This question already has answers here:
How to seed an Admin user in EF Core 2.1.0?
(7 answers)
Closed 3 years ago.
I have managed to seed the admin's details like the username and password, so they appear in the table. However, the issue I am having is the role "admin" is not being saved anywhere in the table. Am I missing something here? I am new to asp.net core so I'm just trying to wrap my head around it.
Below is my seeding class:
public class ApplicationDbInitializer
{
public static void SeedUsers(UserManager<IdentityUser> userManager)
{
if (userManager.FindByEmailAsync("abc#outlook.com").Result == null)
{
IdentityUser user = new IdentityUser
{
UserName = "abc#outlook.com",
Email = "abc#outlook.com"
};
IdentityResult result = userManager.CreateAsync(user, "Passwordtest123!").Result;
if (result.Succeeded)
{
userManager.AddToRoleAsync(user, "Admin").Wait();
}
}
}
}
Below is my configure method signature:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager<IdentityUser> userManager)
Below is me invoking my seed method:
ApplicationDbInitializer.SeedUsers(userManager);
Below is my add identity:
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<RestaurantWebContext>();
Is there something in the code that is missing, I can't see admin show up in the role table or the user table.
You need to seed the Roles as well, then link the User to the Role you want.
Check this answer for more information of how you can seed the data.
You can view my full code here
Below is an example
var user = new User
{
Id = new Guid("a1add451-7dd2-46fd-9877-1996e3f1fb4c").ToString(),
Email = "",
NormalizedEmail = "".ToUpper(),
UserName = "",
NormalizedUserName = "tony5".ToUpper(),
EmailConfirmed = true,
PhoneNumberConfirmed = true,
LockoutEnabled = false,
SecurityStamp = Guid.NewGuid().ToString()
};
using (var context = new ApplicationDbContext(
serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
{
var roles = new[]
{"Owner", "Administrator", "Editor", "ContentWriter"};
var roles1 = new[]
{"Administrator"};
var roles2 = new[]
{"Editor"};
var roles4 = new[]
{"Owner", "Administrator"};
if (!context.Roles.Any())
{
foreach (var role in roles)
{
var roleStore = new RoleStore<ApplicationRole>(context);
await roleStore.CreateAsync(new ApplicationRole
{
Name = role,
NormalizedName = role.ToUpper()
});
}
}
if (!context.Users.Any())
{
await SeedUser(user, context, serviceProvider, roles4);
}
}
private static async Task SeedUser(
User user,
ApplicationDbContext context,
IServiceProvider serviceProvider,
string[] roles)
{
var password = new PasswordHasher<User>();
var hashed = password.HashPassword(user, "123456");
user.PasswordHash = hashed;
var userStore = new UserStore<User>(context);
await userStore.CreateAsync(user);
await EnsureRole(serviceProvider, user.Email, roles);
await context.SaveChangesAsync();
}
Related
I tried to use roles in my blazor project. I more or less orientated myself by this https://code-maze.com/using-roles-in-blazor-webassembly-hosted-applications/ tutorial
I created roles in the database and everything, like login and such, worked. I added
services.AddIdentityServer().AddApiAuthorization<ApplicationUser, ApplicationDBContext>(opt =>
{
opt.IdentityResources["openid"].UserClaims.Add("role");
opt.ApiResources.Single().UserClaims.Add("role");
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("role");
in the Startup.cs file. To create a "role" claim for my user, but when I log in I don't see a role claim.
s_hash: nz4meiUsDlXBa8pOfipRmw
sid: 792E67E7F29DF24F13045EECD0DCC6C2
sub: e999a53a-8c76-4737-a202-dabe9e9eeceb
auth_time: 1628245115
idp: local
amr: ["pwd"]
preferred_username: waiter2000#gmx.de
name: waiter2000#gmx.de
The problem is that I have not been able to use role-based authorization for hours because somehow my application does not create a claim field as it should.
#HenriquePombo I thought the role will be assigned by login automatically. Generally I have a Login which is assigned to a role by registration in Register.cshtml.cs.
string UserRole = Request.Form["RoleSelect"];
var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };
var result_CreateAsync = await _userManager.CreateAsync(user, Input.Password);
var result_AddToRolesAsync = await _userManager.AddToRolesAsync(user, new[] { UserRole });
#HenriquePombo
I added the class like in tutorial explained
public class CustomUserFactory : AccountClaimsPrincipalFactory<RemoteUserAccount>
{
public CustomUserFactory(IAccessTokenProviderAccessor accessor)
: base(accessor)
{
}
public async override ValueTask<ClaimsPrincipal> CreateUserAsync(
RemoteUserAccount account,
RemoteAuthenticationUserOptions options)
{
var user = await base.CreateUserAsync(account, options);
var claimsIdentity = (ClaimsIdentity)user.Identity;
if (account != null)
{
MapArrayClaimsToMultipleSeparateClaims(account, claimsIdentity);
}
return user;
}
private void MapArrayClaimsToMultipleSeparateClaims(RemoteUserAccount account, ClaimsIdentity claimsIdentity)
{
foreach (var prop in account.AdditionalProperties)
{
var key = prop.Key;
var value = prop.Value;
if (value != null &&
(value is JsonElement element && element.ValueKind == JsonValueKind.Array))
{
claimsIdentity.RemoveClaim(claimsIdentity.FindFirst(prop.Key));
var claims = element.EnumerateArray()
.Select(x => new Claim(prop.Key, x.ToString()));
claimsIdentity.AddClaims(claims);
}
}
}
}
and I added the service to the client Program.cs
builder.Services.AddApiAuthorization().AddAccountClaimsPrincipalFactory<CustomUserFactory>();
Please keep in mind I was using Blazor Server so some things might differ (especially on startup, I would say). Also some specific things you could alter for the example you are using (for instance I'm using SessionStorage, etc.)
Also, I followed this Blazor Tutorial playlist Blazor Tutorial for helping me with those kinds of things. Best regards.
Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
//Allow the use of Authentication and Authorization in my program
app.UseAuthentication();
app.UseAuthorization();
}
public void ConfigureServices(IServiceCollection services)
{
...
//Service I added for handling authentication related stuff
services.AddScoped<AuthenticationStateProvider, CustomAuthenticationStateProvider>();
}
Class CustomAuthenticationStateProvider
public async Task MarkUserAsAuthenticated(UserModel user)
{
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, user.FirstName + " " + user.LastName),
new Claim(ClaimTypes.Email, user.EmailAddress),
new Claim(Claims.UserCredentials, user.UserCredentials),
}, "apiauth_type");
var roles = await GetUserRoles(user.UserCredentials);
foreach(var role in roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, role.Name));
}
var user1 = new ClaimsPrincipal(identity);
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(user1)));
foreach (var claim in identity.Claims)
{
await _sessionStorageService.SetItemAsStringAsync(claim.Type, claim.Value);
}
}
and then somewhere:
private readonly AuthenticationStateProvider _customAuthenticationStateProvider;
...
await ((CustomAuthenticationStateProvider)_customAuthenticationStateProvider).MarkUserAsAuthenticated(loginUser);
I was able to solve the problem myself. I will now give up programming forever and bury myself. It is a shame. Sooo... I have "Roles" instead of a single "Role" in the Register.html.cs. Differnt is:
_userManager.AddToRoleAsync(user, UserRole )
and
await _userManager.AddToRolesAsync(user, new[] { UserRole });
Now when I created a new user with this small difference, everything works fine.
Thx #HenriquePombo thank you very much for your time and advice.
i want to create a new role for admin . i am using .net framework mvc 5 but when i run the application it does not create the user and does not save it in the database although the role with id is created successfully and i can see it through the database.
my code is written in startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
CreateUserAndRoles();
}
public void CreateUserAndRoles()
{
ApplicationDbContext context = new ApplicationDbContext();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
if (!roleManager.RoleExists("Admin"))
{
var role = new IdentityRole("Admin");
roleManager.Create(role);
var user = new ApplicationUser();
user.UserName = "admin";
user.Email = "admin#admin.com";
string password = "12345";
var newuser = userManager.Create(user, password);
if (newuser.Succeeded)
{
userManager.AddToRole(user.Id, "Admin");
}
}
}
}
I get an Exception when I try to add a new user to a role:
ArgumentException: Entity type 'IdentityUserRole' is defined with a single key property, but 2 values were passed to the 'DbSet.Find' method.
This was thrown at the line below
userManager.AddToRoleAsync(user, "Admin");
This is the method in Startup class:
private async Task CreateRoles(IServiceProvider serviceProvider) {
//adding custom roles
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole<int>> > ();
var userManager = serviceProvider.GetRequiredService<UserManager<UserEntity>>();
string[] roleNames = { "Admin", "Manager", "User" };
IdentityResult roleResult;
foreach (var roleName in roleNames) {
//creating the roles and seeding them to the database
var roleExist = await roleManager.RoleExistsAsync(roleName);
if (!roleExist) {
roleResult = await roleManager.CreateAsync(
new IdentityRole<int> {
Name = roleName,
NormalizedName = roleName.ToUpper()
});
}
}
//creating a super user who could maintain the web app
var poweruser = new UserEntity {
UserName = Configuration["AdminUserName"],
Email = Configuration["AdminUserEmail"],
Password = Configuration["AdminUserPassword"],
ResidendceId = int.Parse(Configuration["AdminUserCountryId"])
};
string UserPassword = Configuration["AdminUserPassword"];
UserEntity user = await userManager.FindByEmailAsync(Configuration["AdminUserEmail"]);
if (user == null) {
var createPowerUser = await userManager.CreateAsync(poweruser);
user = poweruser;
}
var adminRoleList = await userManager.GetUsersInRoleAsync("Admin");
if (user != null && !adminRoleList.Any(u => u.Email == user.Email)) {
//here we tie the new user to the "Admin" role
await userManager.AddToRoleAsync(user, "Admin");
}
}
Any idea?
Thanks
In your DbContext class add the following
builder.Entity<IdentityUserRole<int>>(b =>
{
b.HasKey(i => new {i.UserId, i.RoleId});
});
This should give DbFind the two keys that it is looking for.
Please Use from string instead of int--->
builder.Entity<IdentityUserRole<string>>(b =>
{
b.HasKey(i => new {i.UserId, i.RoleId});
});
I have finished doing this tutorial/sample, on how to use MySQL database with ASP.NET identity:
http://www.asp.net/identity/overview/getting-started/aspnet-identity-using-mysql-storage-with-an-entityframework-mysql-provider
Now I would like to add functionality wich creates Admin user on start with role Admin. In the past I was using SimpleMembership and local 'SQL Server Database'and it was quite simple, now I'm trying to do this by adding user in 'MySqlInitializer'. Here's a code I'm trying to make work:
MySqlInitializer
namespace IdentityMySQLDemo
{
public class MySqlInitializer : IDatabaseInitializer<ApplicationDbContext>
{
public void InitializeDatabase(ApplicationDbContext context)
{
if (!context.Database.Exists())
{
// if database did not exist before - create it
context.Database.Create();
}
else
{
// query to check if MigrationHistory table is present in the database
var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery<int>(
string.Format(
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '__MigrationHistory'",
"17817412_kontadb"));
// if MigrationHistory table is not there (which is the case first time we run) - create it
if (migrationHistoryTableExists.FirstOrDefault() == 0)
{
context.Database.Delete();
context.Database.Create();
}
}
Seed(context);
}
protected void Seed(ApplicationDbContext context)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
const string name = "admin#example.com";
const string password = "Password";
const string roleName = "Admin";
//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null)
{
role = new IdentityRole(roleName);
var roleresult = roleManager.Create(role);
}
var user = userManager.FindByName(name);
if (user == null)
{
user = new ApplicationUser { UserName = name, Email = name };
var result = userManager.Create(user, password);
result = userManager.SetLockoutEnabled(user.Id, false);
}
// Add user admin to Role Admin if not already added
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name))
{
var result = userManager.AddToRole(user.Id, role.Name);
}
}
}
}
IdentityModels
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace IdentityMySQLDemo.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
static ApplicationDbContext()
{
Database.SetInitializer(new MySqlInitializer());
}
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
I don't know why it don't want to create Admin user on application start, I was trying to move this code to "Configuration" or 'MySQLConfiguration" in Migrations folder. I was also trying to create all table first and than add Admin user with this, but it still didn't work. Please tell me where is my stupid mistake in this code?
It looks like ther maybe a missing context.SaveChanges() or three.
Is the problem with your seed method? If the issue is when your running your update-database command in the NuGet package manager console, if there is no call to context.SaveChanges() then it won't update the DB.
You'll also need to call it 3 times..
after the role is created
after the user is created
after the user is assigned to the role
I'm a relatively newbie myself to C# / ASP.NET MVC so am not 100% if this is the correct fix as unable to test my thoughts currently, but seems to be a similar problem I've faced in the past.
UPDATE
I've had a play around and this successfully updated the 3 tables as part of the seed method.
I think one of the other problems is that rather than calling a method in a couple of places, you were just assigning them into a variable and then not using. For example in this snippet:
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name))
{
var result = userManager.AddToRole(user.Id, role.Name);
}
I changed it to:
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name))
{
userManager.AddToRole(user.Id, role.Name);
}
Thus removing var result =
Here is the full code:
protected override void Seed( MySqlInitializer context)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext("DefaultConnection")));
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext("DefaultConnection")));
const string name = "admin#example.com";
const string password = "Password";
const string roleName = "Admin";
//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null)
{
role = new IdentityRole(roleName);
roleManager.Create(role);
}
context.SaveChanges();
var user = userManager.FindByName(name);
if (user == null)
{
user = new ApplicationUser { UserName = name, Email = name };
userManager.Create(user, password);
userManager.SetLockoutEnabled(user.Id, false);
}
context.SaveChanges();
// Add user admin to Role Admin if not already added
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name))
{
userManager.AddToRole(user.Id, role.Name);
}
context.SaveChanges();
}
In some ways I would like to thank you as by helping you, I've helped myself :)
There is very little documentation about using the new Asp.net Identity Security Framework.
I have pieced together what I could to try and create a new Role and add a User to it. I tried the following: Add role in ASP.NET Identity
which looks like it may have gotten the info from this blog: building a simple to-do application with asp.net identity and associating users with to-does
I have added the code to a Database Initializer that is run whenever the model changes. It fails on the RoleExists function with the following error:
System.InvalidOperationException occurred in mscorlib.dll
The entity type IdentityRole is not part of the model for the current context.
protected override void Seed (MyContext context)
{
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
// Create Admin Role
string roleName = "Admins";
IdentityResult roleResult;
// Check to see if Role Exists, if not create it
if (!RoleManager.RoleExists(roleName))
{
roleResult = RoleManager.Create(new IdentityRole(roleName));
}
}
Any help is appreciated.
Here we go:
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if(!roleManager.RoleExists("ROLE NAME"))
{
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "ROLE NAME";
roleManager.Create(role);
}
Verify you have following signature of your MyContext class
public class MyContext : IdentityDbContext<MyUser>
Or
public class MyContext : IdentityDbContext
The code is working for me, without any modification!!!
Here is the complete article describing how to create roles, modify roles, delete roles and manage roles using ASP.NET Identity. This also contains the User interface, controller methods, etc.
http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc
In ASP.NET 5 rc1-final, I did following:
Created ApplicationRoleManager (in similar manner as there is ApplicationUser created by template)
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(
IRoleStore<IdentityRole> store,
IEnumerable<IRoleValidator<IdentityRole>> roleValidators,
ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors,
ILogger<RoleManager<IdentityRole>> logger,
IHttpContextAccessor contextAccessor)
: base(store, roleValidators, keyNormalizer, errors, logger, contextAccessor)
{
}
}
To ConfigureServices in Startup.cs, I added it as RoleManager
services.
.AddIdentity<ApplicationUser, IdentityRole>()
.AddRoleManager<ApplicationRoleManager>();
For creating new Roles, call from Configure following:
public static class RoleHelper
{
private static async Task EnsureRoleCreated(RoleManager<IdentityRole> roleManager, string roleName)
{
if (!await roleManager.RoleExistsAsync(roleName))
{
await roleManager.CreateAsync(new IdentityRole(roleName));
}
}
public static async Task EnsureRolesCreated(this RoleManager<IdentityRole> roleManager)
{
// add all roles, that should be in database, here
await EnsureRoleCreated(roleManager, "Developer");
}
}
public async void Configure(..., RoleManager<IdentityRole> roleManager, ...)
{
...
await roleManager.EnsureRolesCreated();
...
}
Now, the rules can be assigned to user
await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync(User.GetUserId()), "Developer");
Or used in Authorize attribute
[Authorize(Roles = "Developer")]
public class DeveloperController : Controller
{
}
As an improvement on Peters code above you can use this:
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (!roleManager.RoleExists("Member"))
roleManager.Create(new IdentityRole("Member"));
My application was hanging on startup when I used Peter Stulinski & Dave Gordon's code samples with EF 6.0. I changed:
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
to
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(**context**));
Which makes sense when in the seed method you don't want instantiate another instance of the ApplicationDBContext. This might have been compounded by the fact that I had Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer()); in the constructor of ApplicationDbContext
Roles View Model
public class RoleViewModel
{
public string Id { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "RoleName")]
public string Name { get; set; }
}
Controller method
[HttpPost]
public async Task<ActionResult> Create(RoleViewModel roleViewModel)
{
if (ModelState.IsValid)
{
var role = new IdentityRole(roleViewModel.Name);
var roleresult = await RoleManager.CreateAsync(role);
if (!roleresult.Succeeded)
{
ModelState.AddModelError("", roleresult.Errors.First());
return View();
}
return RedirectToAction("some_action");
}
return View();
}
I wanted to share another solution for adding roles:
<h2>Create Role</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<span class="label label-primary">Role name:</span>
<p>
#Html.TextBox("RoleName", null, new { #class = "form-control input-lg" })
</p>
<input type="submit" value="Save" class="btn btn-primary" />
}
Controller:
[HttpGet]
public ActionResult AdminView()
{
return View();
}
[HttpPost]
public ActionResult AdminView(FormCollection collection)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (roleManager.RoleExists(collection["RoleName"]) == false)
{
Guid guid = Guid.NewGuid();
roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = collection["RoleName"] });
}
return View();
}
If you are using the default template that is created when you select a new ASP.net Web application and selected Individual User accounts as Authentication and trying to create users with Roles so here is the solution. In the Account Controller's Register method which is called using [HttpPost], add the following lines in if condition.
using Microsoft.AspNet.Identity.EntityFramework;
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
var roleManager = new RoleManager<IdentityRole>(roleStore);
if(!await roleManager.RoleExistsAsync("YourRoleName"))
await roleManager.CreateAsync(new IdentityRole("YourRoleName"));
await UserManager.AddToRoleAsync(user.Id, "YourRoleName");
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
This will create first create a role in your database and then add the newly created user to this role.
public static void createUserRole(string roleName)
{
if (!System.Web.Security.Roles.RoleExists(roleName))
{
System.Web.Security.Roles.CreateRole(roleName);
}
}
the method i Use for creating roles is below, assigning them to users in code is also listed. the below code does be in "configuration.cs" in the migrations folder.
string [] roleNames = { "role1", "role2", "role3" };
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
IdentityResult roleResult;
foreach(var roleName in roleNames)
{
if(!RoleManager.RoleExists(roleName))
{
roleResult = RoleManager.Create(new IdentityRole(roleName));
}
}
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
UserManager.AddToRole("user", "role1");
UserManager.AddToRole("user", "role2");
context.SaveChanges();