Smoking monkey
Smoking monkey

Reputation: 323

How to get the roles of current logged-in user in Asp.net Mvc?

I am writing the code to get roles in Login method inside the if-condition but its not returning the roles of the user.

 public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.Email, model.Password, persistCookie: model.RememberMe))
        {

            List<string> r = Roles.GetRolesForUser().ToList();
            if(r.Contains("Admin"))
            {
                return RedirectToAction("About", "Home");
            }
            return RedirectToLocal(returnUrl);
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }

Upvotes: 1

Views: 1165

Answers (1)

JK.
JK.

Reputation: 21808

When you call WebSecurity.Login the user's authentication and role data is not populated automatically. Instead they are written to the authentication cookie and can only be read on the next request.

This means you can only read from Roles.GetRolesForUser() after the user has been redirected to the next page after login (usually Home/Index). This is because the next request that the user makes (whatever it might be) will now have the authentication cookie attached to it.

The current request (~/login.aspx) does not have any authentication cookie attached, so Roles.GetRolesForUser() and similar functions will always return nothing.

Upvotes: 2

Related Questions