The code below is meant to store this user (I'm using Visual Studio and SQL Server Management Studio 2018). However, when I go onto the server and type SEARCH * FROM dbo.AspNetUsers, the user I created does not come up on SSMS. I'm pretty sure my code should work but I don't know why I can't see it in SSMS.
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
CreateUserAndRoles();
}
public void CreateUserAndRoles()
{
ApplicationDbContext context = new ApplicationDbContext();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>());
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());
if (!roleManager.RoleExists("SuperAdmin"))
{
//Create Super Admin Role
var role = new IdentityRole("SuperAdmin");
roleManager.Create(role);
//Create Default User
var user = new ApplicationUser();
user.UserName = "admin#swansea.ac.uk";
user.Email = "admin#swansea.ac.uk";
string pwd = "Password#2019";
var newuser = userManager.Create(user, pwd);
if (newuser.Succeeded)
{
userManager.AddToRole(user.Id, "SuperAdmin");
}
}
}
Related
with VS 2015 I've created a little MVC App with the default authentification stuff.
I've changed nothing but the code in the registration action of the account controller:
var context = new ApplicationDbContext();
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
if (!roleManager.RoleExists("Administrator"))
{
roleManager.Create(new IdentityRole("Administrator"));
}
if (!roleManager.RoleExists("User"))
{
roleManager.Create(new IdentityRole("User"));
}
if (context.Users.Count() == 1)
{
userManager.AddToRole(user.Id, "Administrator");
} else
{
try
{
userManager.AddToRole(user.Id, "User");
}
catch (Exception ex)
{
throw new Exception("Error assigning role: " + ex.Message);
}
}
The first registrated user becomes an "Administrator". Though the "userManager.AddToRole(user.Id, "User");" doesn't throw an exception no following registrated user is assigned to that role (checked the table and also per Authorize(Role...).
I can't figure out what's wrong here.
I've figured it out. I've used generic email addresses with an "+" in the user name, e.g. user+01#mydomain.com. This doesn't cause trouble while registrating and throws no exception when try/catch the AddRoleTo method but in the result stack of the AddRoleTo appears an error that only chars and numbers are allowed for user name.
I'm trying to initialize some test data in my database, and having some problems adding password to the ApplicationUser in Identity Framework.
When I have done this earlier, I have used the seed method like this:
protected override void Seed(ApplicationDbContext db)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
var adminuser = new ApplicationUser { Email = "admin#test.no", UserName = "admin#test.no", FirstName = "admin", LastName = "test" };
userManager.Create(adminuser, "Password1.");
userManager.AddToRole(adminuser.Id, role:"admin");
}
but as the seed method is not supported in dotnet core I have tried to add the dummy data in the following way:
using (var serviceScope =
app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
db.Database.EnsureCreated();
db.AddRange(
new ApplicationUser { UserName = "ola#nordmann.no", Email = "ola#nordmann.no" },
new ApplicationUser { UserName = "test#test.no", Email = "test#test.no" }
);
db.SaveChanges();
I have also tried to use the same method I used in the seed method, but that doesn't work either as I get the following error message on the line were I add result1 to the database:
cannot convert from 'System.Threading.Tasks.Task' to 'Server.Models.ApplicationUser
using (var serviceScope =
app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var db = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
var userManager = app.ApplicationServices.GetService<UserManager<ApplicationUser>>();
var au1 = new ApplicationUser { UserName = "test#test.no", Email = "test#test.no" };
var result1 = userManager.CreateAsync(au1, "Test123");
db.Users.Add(result1);
You can use PasswordHasher in combination with user.
i.e.
var user = new User();
var hasher = new PasswordHasher<User>();
db.AddRange(
new ApplicationUser { UserName = "ola#nordmann.no", Email = "ola#nordmann.no", PasswordHash = hasher.HashPassword(user, "Password1") },
);
db.SaveChanges();
If anyone else should be interested, I ended up with the following solution:
public async Task CreateUsersAndRoles(IServiceScope serviceScope)
{
var userManager = serviceScope.ServiceProvider.GetService<UserManager<ApplicationUser>>();
await userManager.CreateAsync(new ApplicationUser { UserName = "ola#nordmann.no", Email = "ola#nordmann.no"}, "Password1.");
}
and call on this method within the Configure method in the startup file like this:
await CreateUsersAndRoles(app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope());
I am creating a new User using ASP.NET Core Identity as follows:
new User {
Email = "john#company.com",
Name = "John"
}
await userManager.CreateAsync(user, "password");
I need to add a Claims when creating the user. I tried:
new User {
Email = "john#company.com",
Name = "John",
Claims = new List<Claim> { /* Claims to be added */ }
}
But Claims property is read only.
What is the best way to do this?
You can use UserManager<YourUser>.AddClaimAsync method to add a claims to your user
var user = new User {
Email = "john#company.com",
Name = "John"
}
await userManager.CreateAsync(user, "password");
await userManager.AddClaimAsync(user, new System.Security.Claims.Claim("your-claim", "your-value"));
Or add claims to the user Claims collection
var user = new User {
Email = "john#company.com",
Name = "John"
}
user.Claims.Add(new IdentityUserClaim<string>
{
ClaimType="your-type",
ClaimValue="your-value"
});
await userManager.CreateAsync(user);
I am successful to create new user account using Google Directory API in .Net platform, but now I need to add that created user to Organization Unit and Group. I see the API details in this link to add the user to Organization Unit but any example showing insertion to Organization Unit would be greatly appreciated.
Updated with working code: Below is the code to create new user account using Directory API:
String serviceAccountEmail = ".........#developer.gserviceaccount.com";
X509Certificate2 certificate = new X509Certificate2(#"C:\key.p12", "secret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[]
{
DirectoryService.Scope.AdminDirectoryUser
},
User = "test#example.com",
}.FromCertificate(certificate));
var ser = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Google Account",
});
try
{
var user = new Google.Apis.Admin.Directory.directory_v1.Data.User()
{
Name = new Google.Apis.Admin.Directory.directory_v1.Data.UserName()
{
GivenName = FirstName.Text,
FamilyName = LastName.Text
},
Password = password
};
User newUser = new User();
UserName newUserName = new UserName();
newUser.PrimaryEmail = Email.Text;
newUserName.GivenName = FirstName_txt.Text;
newUserName.FamilyName = LastName_txt.Text;
newUser.Name = newUserName;
newUser.Password = password;
//Adding User to OU:
newUser.OrgUnitPath = "/Employee";
User results = ser.Users.Insert(newUser).Execute();
//Adding User to Group:
Member newMember = new Member();
newMember.Email = Email.Text;
newMember.Role = "MEMBER";
newMember.Kind = "admin#directory#member";
api.Members.Insert(newMember, "Employee#example.com").Execute();
Any idea how to insert the created user in Organization Unit and Group using Directory API?
To insert the new user into a Organization Unit just set the OU path when you create the user.
User newUser = new User();
UserName newUserName = new UserName();
newUser.PrimaryEmail = Email.Text;
newUserName.GivenName = FirstName_txt.Text;
newUserName.FamilyName = LastName_txt.Text;
newUser.Name = newUserName;
newUser.Password = password;
**newUser.OrgUnitPath ="\My\Organization\Unit\path\";**
User results = ser.Users.Insert(newUser).Execute();
Now your user has been added to the OU path.
To add a member into a group see the following code.
Member newMember = new Member();
newMember.Email = userKey;//email of the user that you want to add
newMember.Role = "MEMBER";
newMember.Type = "USER";
newMember.Kind = "admin#directory#member";
ser.Members.Insert(newMember, "MyDestinationGroup#mydomain").Execute();
that's it.
Note: you must review the scopes for the correct permissions.
Hope this help you.
I came across a problem for seeding the database with Identity v2. I separated out the IdentityModel from the MVC5 project to my Data Access Layer where I setup EF Migrations as well. So I commented out the code which use inside "IdentityConfig.cs" to create initial user and put the code inside my seed database that looks like this
protected override void Seed(Repository.DataContext.IdentityDb context)
{
// var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
// var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
var owinContext = new OwinContext();
var userManager = owinContext.GetUserManager<ApplicationUserManager>();
var roleManager = owinContext.Get<ApplicationRoleManager>();
const string name = "admin#admin.com";
const string password = "Admin#123456";
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);
}
}
Now when I am running command update-database, I got an error
Value cannot be null.
Parameter name: manager
It looks like, I am getting null in these two lines of code
var userManager = owinContext.GetUserManager<ApplicationUserManager>();
var roleManager = owinContext.Get<ApplicationRoleManager>();
Any suggestion please?
This is the way to avoid using an OWIN context:
protected override void Seed(Repository.DataContext.IdentityDb context)
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
var user = new ApplicationUser { UserName = "sallen" };
userManager.Create(user, "password");
roleManager.Create(new IdentityRole { Name = "admin" });
userManager.AddToRole(user.Id, "admin");
}
I got this working by using:
protected override void Seed(ApplicationDbContext context)
{
context.Configuration.LazyLoadingEnabled = true;
//var userManager = HttpContext.Current
// .GetOwinContext().GetUserManager<ApplicationUserManager>();
//var roleManager = HttpContext.Current
// .GetOwinContext().Get<ApplicationRoleManager>();
var roleStore = new RoleStore<ApplicationRole, int, ApplicationUserRole>(context);
var roleManager = new RoleManager<ApplicationRole, int>(roleStore);
var userStore = new UserStore<ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>(context);
var userManager = new UserManager<ApplicationUser, int>(userStore);
...
Hi Under the Startup class please make sure that you have call
app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContextApplicationUserManager.Create);
app.CreatePerOwinContextApplicationSignInManager.Create);
app.CreatePerOwinContext(ApplicationRoleManager.Create);
Latest stuff is all async & uses Claims.
Here's what worked for me with migrations to add a super user if none exists ...
protected override void Seed(Holos.Service.Models.ApplicationDbContext context)
{
var email = "xxxx#xxxx.com";
var password = "xxxxx";
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new ApplicationUserManager(userStore);
var user = userManager.FindByEmailAsync(email).Result;
if (user == null)
{
var adminUser = new ApplicationUser() { Email = email, UserName = email };
var result = userManager.CreateAsync(adminUser, password);
result.Wait();
userManager.AddClaimAsync(adminUser.Id, new Claim("Read", "*")).Wait();
userManager.AddClaimAsync(adminUser.Id, new Claim("Create", "*")).Wait();
userManager.AddClaimAsync(adminUser.Id, new Claim("Update", "*")).Wait();
userManager.AddClaimAsync(adminUser.Id, new Claim("Delete", "*")).Wait();
userManager.AddClaimAsync(adminUser.Id, new Claim("UserType", "SuperUser")).Wait();
}
}