1

From my understanding is that when a user creates a new account in ASP.NET MVC, the method to handle this would be the Register method located in the AccountController class of any MVC Solution. This is how the current method of my class looks like:

// GET: /Account/Register [AllowAnonymous] public ActionResult Register() { return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return RedirectToAction("Index", "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } 

However from what I noticed is that there is no code concerning dealing with Roles. My goal is to set a role for the first user to be created and make it an Admin role. All users that would register after that should differ from that role. How could I approach this in this code?

Edit: Would I have to use my Seed method of Migrations\Configuration.cs in order to achieve this instead? If so, how should my Seed method need to look like?

6
  • Yes, you enter the user and role through the back-end. Seeding is one way you could also run a query in SSMS. Commented May 2, 2017 at 23:31
  • You can assign roles to the newly created user by adding the line: UserManager.AddToRole(user.Id, "SomeRoleName"); But you'll need to create the role first. In your seeding you can do the same, but set the role to "Admin". Commented May 3, 2017 at 0:25
  • Wouldn't a role name require a RoleId, thus adding a role as string format to a user would be strange? From what I noticed is that the interim table called AspNetUserRoles uses a property UserId and RoleId. Knowing this I think a role has already to be set and assigned an Id accordingly I thought a User (who has a UserId assinged), should get a RoleId assigned? @RuardvanElburg Commented May 3, 2017 at 0:33
  • That is what I said, you'll need to create the role(s) first. Instead of implementing the RoleManager easiest method is to add the role(s) in AspNetRoles with SSMS. Why is using the string format weird? [Authorize(Roles:) is using the rolenames, not id's. Also the AddToRole accepts a string, not the id. Also, rolenames have to be unique. Commented May 3, 2017 at 0:38
  • I know SSMS is easy to achieve assigning a role to a user, but I want every user to be automatically assigned a role of User (instead of a role with a null value) when a new user is created, so I can make my application working around authorization. Concerning the string part, I was not sure if that is a "secure" way of approaching role assignment but the latter part of your comment made sense. Commented May 3, 2017 at 1:11

1 Answer 1

2

Yes you can use your seed Method for initialized your roles and first admin user. For Example:

 protected override void Seed(ApplicationDbContext context) { //initialized Role context.Roles.AddOrUpdate(r => r.Name, new IdentityRole { Name = "SuperAdmin" }, new IdentityRole { Name = "Admin" }, new IdentityRole { Name = "User" } ); //initialized Admin user if (!context.Users.Any(u => u.UserName == "[email protected]")) { var store = new UserStore<ApplicationUser>(context); var manager = new UserManager<ApplicationUser>(store); var user = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]", PhoneNumber = "+8801717252600", //....... }; manager.Create(user, "aSHIQ!109"); manager.AddToRole(user.Id, "Admin"); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.