87451

Correct way of setting the role for user when he is registered with Identity

Question:

I have a question, I'm new to identity, but still i would like to know what would be the correct way of assigning role to a user when he is registering?

I have here a code:

[HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser() { UserName = model.UserName }; RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())); IdentityRole role = new IdentityRole("Admin"); await RoleManager.CreateAsync(role); // Store Gender as Claim user.Claims.Add(new IdentityUserClaim() { ClaimType = ClaimTypes.Gender, ClaimValue = "Male" }); //user.Roles.Add(new IdentityUserRole() { RoleId=role.Id, UserId=user.Id }); var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { //await UserManager.AddToRoleAsync(user.Id, "Admin"); await SignInAsync(user, isPersistent: false); return RedirectToAction("Index", "Home"); } else { AddErrors(result); } } // If we got this far, something failed, redisplay form return View(model); }

This is just a test code, but basically if i use method UserManager.AddToROleAsync( ...) it works, BUT, it only happens after the user is added, so basically i do twice the roundtrip to database.

I tried doing it with user.Roles.Add(...) but i get an error when running it.

So my question would be what is the most efficient and correct way of doing it?

Answer1:

I don't know if there's a better way. I normally to it the same way as you do, first creating the role (if it doesn't exist), then creating the user, and as a last step adding the user to the role.

To use user.Roles.Add(...) the role must be present. The reason is the database (in this case Entity Framework and SQL Server). When looking closer at the Identity database you'll see that there is a relationship between the <strong>AspNetRoles</strong> and <strong>AspNetUsers</strong> table through the <strong>AspNetUserRoles</strong> table which has the <em>UserId</em> and the <em>RoleId</em> as a key. That means you can't add a user to a role when the user does not exist yet (and vice versa). So in my opinion you have to do twice the roundtrip (if you don't directly work on the context).

Answer2:

This works fine (Asp.Net Core Identity):

var role = await this.roleManager.FindByNameAsync( "Admin" ); var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var userRole = new IdentityUserRole<int> { RoleId = role.Id, }; user.Roles.Add(userRole ); var result = await this.userManager.CreateAsync( user, model.Password);

Recommend

  • add claims to windows identity
  • Angularjs Adal and additional claims or properties for Authorization
  • How to retrieve Google profile picture from logged in user with ASP.Net Core Identity?
  • 500 Internal Server Error in Azure AD B2C
  • How do I include claims into the Access Token retrieved from the Authorize endpoint?
  • Update Asp.Net Claims via SQL statement?
  • How do I inject dependency in owin startup class
  • What is the default consistency level in spring-data-cassandra?
  • SNIReadSync executing between 120-500 ms for a simple query. What do I look for?
  • Missing type map configuration or unsupported mapping after auto code generation on the client
  • Why to use _form.html.erb in rails
  • remove user from group Mac Os X (El Capitan)
  • CakePHP 3 “Login As” wtih Multiple Auth Sessions
  • Asp.Net is looking for the web.config in the wrong place
  • Magento SOAP API v2 shoppingCartProductAdd error “One item of products do not have identifier or sku
  • git receive-pack stops with 0000
  • Making a link stay active displaying hover effect upon click using javascript
  • Server control behaving oddly
  • CAS: Unable to validate ProxyTicketValidator
  • JAX-RS Rest services stopped deploying on Eclipse Glassfish
  • Yii: how to show a field from a related table's related table?
  • How to list all the bucket types in riak?
  • How do i install the cakephp forum plugin by Miles J?
  • How to run .ear file in JBoss 6?
  • What's the point of nonfinal singleton objects in scala?
  • How should I start to implement RESTful web service?
  • How do I correctly parse a URI query string into a name-value collection in C#?
  • Adding Client Certifcate to Service Fabric
  • Symfony2 plaintext users don't work
  • Why is django manage.py syncdb failing to create new columns on my development server?
  • Changing Jupyter Notebook start up folder by modifying “start in” not working any more
  • Configure nginx to return different files to different authenticated users with the same URI
  • Authentication failed with Azure Active Directory in Windows Phone
  • How to override value that appears in a dropdown in the rails_admin gem
  • ThreadStatic in asynchronous ASP.NET Web API
  • Allowing both email and username for authentication
  • Angular 2 constructor injection vs direct access
  • Java static initializers and reflection
  • Android Google Maps API OnLocationChanged only called once
  • UserPrincipal.Current returns apppool on IIS