Search code examples
asp.net-mvcasp.net-identityroles

ASP.NET MVC Identity. Unable to add Roles to Users with special characters


In my MVC web app, I am using ASP Identity for User log ins and also for Role based authorization.

The problem I am facing is adding a role to a user with an email that has a special character. eg. test'[email protected]

I can Create/Register the user with the special character with no problem, the problem is only occurs when I attempt to add a role to that specific user.

I have tried altering the the identity config file to for User Validator

  manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

Here is the code for adding a role to a User.

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult RoleAddToUser(string UserName, string RoleName)
    {
        var context = new HolidayTracker.Models.ApplicationDbContext();

        if (context == null)
        {
            throw new ArgumentNullException("context", "Context must not be null.");
        }

        ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

        var userStore = new UserStore<ApplicationUser>(context);
        var userManager = new UserManager<ApplicationUser>(userStore);
        userManager.AddToRole(user.Id, RoleName);


        ViewBag.Message = "Role created successfully !";

        // Repopulate Dropdown Lists
        var rolelist = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name, Text = rr.Name }).ToList();
        ViewBag.Roles = rolelist;
        var userlist = context.Users.OrderBy(u => u.UserName).ToList().Select(uu =>
        new SelectListItem { Value = uu.UserName, Text = uu.UserName }).ToList();
        ViewBag.Users = userlist;

        return View("Index");
    }

I have added breakpoints and the action completes successfully but I think the problem is the role is being created but not for not for that specific character in the username. i.e. It is Replacing the "'" with other character before adding a role hence why that role is not being assigned to that user.

The expected outcome would be to have the role added to the user despite the special character being in the user name.

Note: as of now, this seems to be a problem with apostrophes. Also User are based of Emails.


Solution

  • So thanks to the help of @CodeCaster, I was able to find the route problem and added a validator.

      public ActionResult RoleAddToUser(string UserName, string RoleName)
        {
            var context = new HolidayTracker.Models.ApplicationDbContext();
    
            if (context == null)
            {
                throw new ArgumentNullException("context", "Context must not be null.");
            }
    
            ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
    
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);
            userManager.UserValidator = new UserValidator<ApplicationUser>(userManager) { AllowOnlyAlphanumericUserNames = false };
            userManager.AddToRole(user.Id, RoleName);
            var Check = userManager.AddToRole(user.Id, RoleName);
    
            ViewBag.Message = "Role created successfully !";
    
            // Repopulate Dropdown Lists
            var rolelist = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name, Text = rr.Name }).ToList();
            ViewBag.Roles = rolelist;
            var userlist = context.Users.OrderBy(u => u.UserName).ToList().Select(uu =>
            new SelectListItem { Value = uu.UserName, Text = uu.UserName }).ToList();
            ViewBag.Users = userlist;
    
            return View("Index");
        }