1

I am building an MVC5 application with ASP.NET Identity 2.0 and EF 6.1.1.

This is part of my current Login method:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
            return View(model);

        var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: true);
        switch (result)
        {
            case SignInStatus.Success:
                {
                    var user = await UserManager.FindAsync(model.UserName, model.Password);

                    if (user == null)
                        break;

                    if (!UserManager.IsInRole(user.Id, "OfficeUser"))
                        break; // << I always hit this line - even if the user is an OfficeUser

This works fine until I hit UserManager.IsInRole(). This always returns false.

Somewhere I read that IsInRole() will fail if the corresponding user is not signed in. But since I pass SignInManager.PasswordSignInAsync() I believe this should be fine.

And yes, I have checked the database many times and very carefully ;) My test user and my test role "OfficeUser" are definitely assigned to each other.

Does anybody have an idea?

Ingmar
  • 1,525
  • 6
  • 34
  • 51

1 Answers1

7

I had same kind of issue, then I got work it as below. The reason seems to be, the user not completely signin or completed all authentication process in this stage.

case SignInStatus.Success:
                {
                    var user = await UserManager.FindAsync(model.UserName, model.Password);
                    var roles = await UserManager.GetRolesAsync(user.Id)

                    if (user == null)
                        break;

                    if (roles.Contains("OfficeUser"))
                        break; // << I always hit this line - even if the user is an OfficeUser
DSR
  • 4,588
  • 29
  • 28