I used following method to create two roles and two users when my web app starts (In Application_Start() in Global.asax.cs).
However the Administrator role is being created but not the User role. Similar thing happens for user named Admin#admin.com and user named user#user.net. First one is being created but not the second one.
Here is my code.
void create() {
ApplicationDbContext context = new ApplicationDbContext();
IdentityResult IdRoleResult;
IdentityResult IdUserResult;
var roleStore = new RoleStore<IdentityRole>(context);
var roleMngr = new RoleManager<IdentityRole>(roleStore);
if (!roleMngr.RoleExists("Administrator"))
IdRoleResult = roleMngr.Create(new IdentityRole("Administrator"));
roleStore = new RoleStore<IdentityRole>(context);
roleMngr = new RoleManager<IdentityRole>(roleStore);
if (!roleMngr.RoleExists("User"))
IdRoleResult = roleMngr.Create(new IdentityRole("User"));
var userMngr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var appUser = new ApplicationUser() { UserName = "Admin#admin.com" };
IdUserResult = userMngr.Create(appUser, "pa$$word");
if (IdUserResult.Succeeded)
IdRoleResult = userMngr.AddToRole(appUser.Id, "Administrator");
userMngr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
appUser = new ApplicationUser() { UserName = "user#user.net" };
IdUserResult = userMngr.Create(appUser, "user");
if (IdUserResult.Succeeded)
IdRoleResult = userMngr.AddToRole(appUser.Id, "User");
}
Can anybody tell me, what I've done wrong or any alternative way to perform this.
Thanks in advance.
Updated Code:
void createAdmin() {
ApplicationDbContext context = new ApplicationDbContext();
IdentityResult IdRoleResult;
IdentityResult IdUserResult;
var roleStore = new RoleStore<IdentityRole>(context);
var roleMngr = new RoleManager<IdentityRole>(roleStore);
if (!roleMngr.RoleExists("Administrator")) {
IdRoleResult = roleMngr.Create(new IdentityRole("Administrator"));
if (!IdRoleResult.Succeeded)
throw new Exception("Administrator role wasnt created.");
}
if (!roleMngr.RoleExists("User")) {
IdRoleResult = roleMngr.Create(new IdentityRole("User"));
if (!IdRoleResult.Succeeded)
throw new Exception("User role wasnt created.");
}
var userMngr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
ApplicationUser appUser;
var q = from user in userMngr.Users
where user.UserName == "Admin#admin.com"
select user;
if (q.Count() == 0) {
appUser = new ApplicationUser() { UserName = "Admin#admin.com" };
IdUserResult = userMngr.Create(appUser, "pa$$word");
if (IdUserResult.Succeeded) {
IdRoleResult = userMngr.AddToRole(appUser.Id, "Administrator");
if (!IdRoleResult.Succeeded)
throw new Exception("Admin user wasn't added to Administrator role.");
} else
throw new Exception("Admin user wasn't created.");
}
q = from user in userMngr.Users
where user.UserName == "user#user.net"
select user;
if (q.Count() == 0) {
appUser = new ApplicationUser() { UserName = "user#user.net" };
IdUserResult = userMngr.Create(appUser, "user");
if (IdUserResult.Succeeded) {
IdRoleResult = userMngr.AddToRole(appUser.Id, "User");
if (!IdRoleResult.Succeeded)
throw new Exception("User user wasn't added to User role.");
} else
throw new Exception("User user wasn't created.");
}
}
Here I found that, the code is throwing exception with message "User user wasn't created."
throw new Exception("User user wasn't created.");
I think you should reading error in object result 'IdUserResult', and insert user with function CreateAsync().
Related
I successfully created a new user with this code:
protected void btnRegister_Click(object sender, EventArgs e)
{
// Default UserStore constructor uses the default connection string named: DefaultConnection
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
var user = new IdentityUser() { UserName = txtbxUserName.Text };
IdentityResult result = manager.Create(user, txtbxPassword.Text);
if (result.Succeeded)
{
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
var userIdentity =
manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
Response.Redirect("~/MoneyFly");
}
else
{
litStatusMessage.Text = result.Errors.FirstOrDefault();
}
}
The code created a local database as soon as the user was created.
I want to create roles and add them to users.
I saw a post such as the one below.
https://forums.asp.net/t/2093837.aspx?How+to+implement+Roles+in+ASP+NET+Identity+2+1+in+Webforms
And I struggled to replicate what was done in the code.
That is partially, because it includes an autogenerated class, which I dont have.
ApplicationDbContext context = new ApplicationDbContext();
How do I generate that dbContext. It seems to be vital in the usage of the framework.
For example this line of code uses it to create an instance of RoleStore.
var roleStore = new RoleStore<IdentityRole>(context);
I got the solution.
This solution worked for me.
var roleStore = new RoleStore<IdentityRole>();
var roleMgr = new RoleManager<IdentityRole>(roleStore);
IdentityResult IdRoleResult = roleMgr.Create(new IdentityRole { Name = "Administrator" });
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
IdentityResult IdUserResult = manager.AddToRole( manager.FindByName("vi").Id, "Administrator");
You dont have to provide a DBContext to the RoleStore Constructor.
In my application I am trying to add Roles and then add Users to a particular role. After searching online I have made this snippet
public ActionResult Install1()
{
ClearLocalDev();
RegisterBindingModel model = new RegisterBindingModel();
model.Email = "mohsin#crondale.com";
model.Password = "123Asd?";
model.ConfirmPassword = "123Asd?";
CreateUser(model);
return RedirectToAction("Index", "Home");
}
public void CreateUser(RegisterBindingModel model)
{
ApplicationDbContext context = new ApplicationDbContext();
IdentityResult identityRoleResult;
IdentityResult identityUserResult;
var roleStore = new RoleStore<IdentityRole>(context); // The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
var roleMgr = new RoleManager<IdentityRole>(roleStore);
if (!roleMgr.RoleExists("Admin"))
{
identityRoleResult = roleMgr.Create(new IdentityRole { Name = "Admin" });
}
var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var appUser = new ApplicationUser
{
UserName = model.Email,
Email = model.Email
};
identityUserResult = userMgr.Create(appUser, model.Password);
if (!userMgr.IsInRole(userMgr.FindByEmail(model.Email).Id, "Admin"))
{
identityUserResult = userMgr.AddToRole(userMgr.FindByEmail(model.Email).Id, "Admin");
}
}
This doesn't get. I get an exception. See the comments in the code to see what and where do I get the error.
Does it have something to do with Async?
I am using Azure as my data storage.
This should work for 4.5:
ApplicationDbContext context = new ApplicationDbContext();
IdentityResult identityRoleResult;
IdentityResult identityUserResult;
var roleStore = new RoleStore<IdentityRole>(context);
var roleMgr = new RoleManager<IdentityRole>(roleStore);
if (!roleMgr.RoleExists("SuperAdmin"))
{
identityRoleResult = roleMgr.Create(new IdentityRole { Name = "SuperAdmin" });
}
var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var appUser = new ApplicationUser
{
UserName = "SuperAdminUser#wingtiptoys.com",
Email = "SuperAdminUser#wingtiptoys.com"
};
identityUserResult = userMgr.Create(appUser, "Pa$$word1");
if (!userMgr.IsInRole(userMgr.FindByEmail("SuperAdminUser#xyz.com").Id, "SuperAdmin"))
{
identityUserResult = userMgr.AddToRole(userMgr.FindByEmail("SuperAdminUser#wingtiptoys.com").Id, "SuperAdmin");
}
Have you created the appropriate database tables for identity provider by running ef migrations? To me it seems that you are trying to invoke a context while the underlying database tables have not yet been created.
I suspect the following line will also cause problems:
identityUserResult = userMgr.Create(appUser, model.Password);
Two things you need to check:
You must hash your password before attempting to save it
The password must adhere to the configured password policy before attempting to save it.
I have installed asp.net identity sample https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples and trying to create a new role "SAdmin" with the user "Sadmin#example.com". The user is created but "Sadmin" gets the same role as "Admin"
I have modified IdentityConfig.cs to
//Create User=Admin#Admin.com with password=Admin#123456 in the Admin role
public static void InitializeIdentityForEF(ApplicationDbContext db) {
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
const string name = "admin#example.com";
const string password = "Admin#123456";
const string roleName = "Admin";
const string Sname = "Sadmin#example.com";
const string Spassword = "SAdmin#123456";
const string SroleName = "SAdmin";
//Create Super if it does not exist
var Srole = roleManager.FindByName(SroleName);
if (Srole == null)
{
Srole = new IdentityRole(roleName);
var roleresult = roleManager.Create(Srole);
}
var Suser = userManager.FindByName(Sname);
if (Suser == null)
{
Suser = new ApplicationUser { UserName = Sname, Email = Sname };
var result = userManager.Create(Suser, Spassword);
result = userManager.SetLockoutEnabled(Suser.Id, false);
}
// Add Suser to Role Admin if not already added
var SrolesForUser = userManager.GetRoles(Suser.Id);
if (!SrolesForUser.Contains(Srole.Name))
{
var result = userManager.AddToRole(Suser.Id, Srole.Name);
}
//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);
}
}
The problem is in the code... The following code block is responsible
if (Srole == null)
{
**Srole = new IdentityRole(roleName);**
var roleresult = roleManager.Create(Srole);
}
Change the highlighted line to
**Srole = new IdentityRole(SroleName);**
That should solve it
I have the following code in the Seed method of my Configuration.cs file:
var userStore = new UserStore<ApplicationUser>();
var manager = new UserManager<ApplicationUser>(userStore);
IdentityResult result = manager.Create(new ApplicationUser() { UserName = "test#mail.com", Email = "test#mail.com", Name = "Martin Tracey" }, "password");
if (result.Succeeded) { Console.WriteLine("User created successfully"); }
else {
Console.WriteLine("Something went wrong. result is "+result.ToString());
foreach (var error in result.Errors) Console.WriteLine(error);
}
For whatever reason, the manager.Create call is returning null.
Any idea why this method would ever return null?
I figured it out! It's a very simple solution.
My userStorevariable didn't have a DbContext which would allow it to access and write to the Database. The simple solution is to use the context passed into the Seed method. Works like a charm now! See below:
protected override void Seed(MyFirstWebApplication.Models.ApplicationDbContext context)
{
if( !context.Users.Any( u => u.Email == "test#mail.com" ) )
{
var userStore = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(userStore);
var user = new ApplicationUser() { UserName = "test#mail.com", Email = "test#mail.com", Name = "Martin Tracey" };
IdentityResult result = manager.Create(user, "password");}
}
}
How in mvc 5 I can found out role of logged user?
I made the user by this code
private bool AddUserAndRole()
{
IdentityResult ir;
var rm = new RoleManager<IdentityRole>
(new RoleStore<IdentityRole>(new ApplicationDbContext()));
ir = rm.Create(new IdentityRole("admin"));
var user = new ApplicationUser() { UserName = "Admin" };
var result = UserManager.Create(user, "somepassword");
UserManager.AddToRole(user.Id, "admin");
return true;
}
After I loggin on site by that user. How in controller I can check if that user have role == "admin" or not? I found only one way which doesnt look works fast.
var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
var role = rm.FindByName("admin");
bool result = User.IsInRole(role.Name); //true
Do we have other ways?
bool result = User.IsInRole("admin")
Much easier. :)