-2

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
Clemens
  • 51
  • 11

1 Answers1

0

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.

Clemens
  • 51
  • 11