Home Initializing new user login to role 'User' (EntityFramework/RoleManager)
Reply: 0

Initializing new user login to role 'User' (EntityFramework/RoleManager)

user1102
1#
user1102 Published in June 21, 2018, 12:58 am

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();
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.313324 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO