0

I'm trying to create a user profile with the role of "User" on first login. The code below is creating the user profile, but the role is not being assigned properly. Can you identify what I am missing?

var roleStore = new RoleStore<IdentityRole>(context);
var appRoleManager = new RoleManager<IdentityRole>(roleStore, null, null, null, null, null);
var userStore = new UserStore<IdentityUser>(context);

if (!context.Users.Any(u => u.UserName == userName))
{
    // Create new user
    var newUser = new IdentityUser {
        Email = userName,
        NormalizedEmail = userName,
        UserName = userName,
        NormalizedUserName = userName,
        EmailConfirmed = true,
        PhoneNumberConfirmed = true,
        SecurityStamp = Guid.NewGuid().ToString("D")
    };

    var roleFound = await appRoleManager.FindByNameAsync("User");

    var userRole = new IdentityUserRole<string> {
        RoleId = roleFound.Id
    };

    newUser.Roles.Add(userRole);

    await userStore.CreateAsync(newUser);
}

return NoContent();
Alex Terry
  • 1,992
  • 1
  • 11
  • 17
rahulchawla
  • 101
  • 2
  • 9
  • Can you provide a little more information? It looks like you are assigning the user role. What roles are you seeing on the context after they login? – Alex Terry May 16 '18 at 14:53
  • @ATerry Basically the user is created but there role is N/A (not user) i cannot see them in my dbo.AspNetUserRoles table and I basically have to assign them a user role manually in my portal it doesn't assign them to be a user the first time they log in, therefore the first time they log in page says that they do not have the required authentication – rahulchawla May 16 '18 at 14:57
  • there lockout enabled is set to 1 first time they log in – rahulchawla May 16 '18 at 14:59
  • like i'm setting the emailConfirmed=true in the above code however when I check my initial dbo.AspNetUsers when the users logs in, lockoutEnabled=true and emailConfirmed=false? @ATerry – rahulchawla May 16 '18 at 15:19
  • can anyone give me a suggestion would appreciate – rahulchawla May 17 '18 at 13:50
  • From what I could find, you can't assign a role until after the user is created. https://stackoverflow.com/questions/20841262/adding-a-role-for-user-after-registration-in-mvc-5 this may help. – Alex Terry May 17 '18 at 14:12

0 Answers0