0

So in my .net application I have three controllers

  1. Home
  2. Kitchen
  3. Institution

When the user logs in, I get what controller the user can go. I have defined some roles and using those I get which user needs to go where.

So for example if a user Bob is a cook. When Bob logs in, he is taken to the kitchen dashboard. But if Bob types in the URL ../Home/Dashboard there is nothing stopping him for going in there. What should be done in order to restrict Bob accessing any other url?

Also, when the user logs in should I store the information about his role in session?

What is the best practice for this purpose?

mohsinali1317
  • 4,255
  • 9
  • 46
  • 85
  • You can use a custom `AuthorizeAttribute` for that to check a users role. As for storing information, either session or cookies are used for stuff like that usually (forms auth by default uses cookies) – Mathew Thompson Dec 08 '14 at 12:45
  • any example would be much appreciated. :) – mohsinali1317 Dec 08 '14 at 13:00
  • 1
    Sure, see this question: http://stackoverflow.com/questions/15444630/custom-mvc-authorizeattribute-that-allows-for-multiple-role-membership – Mathew Thompson Dec 08 '14 at 13:46

1 Answers1

1

You can handle all your requirements in an HttpPost Login Action. See comments for further instructios.

[HttpPost]
[AllowAnonymous]
public ActionResult Login(LoginModel model, string returnUrl)
{
    // check first for field validations
    if (!ModelState.IsValid)
        return View(model);

    // validate user agains database
    var user = FindUser(model.UserName, model.Password);
    if (user == null)
    {
        ModelState.AddModelError("", "Invalid username or password.");
        return View(model)
    }

    // user is valid, sign in assuming forms authentication, however it's 
    // best practice to abstract following statement by use of some kind of authentication
    // manager (refer to OWIN framework for a better approach).
    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

    // when returnUrl param is provided
    if (!String.IsNullOrEmpty(returnUrl))
        return Redirect(returnUrl);

    // following 'if' - condition dependent on your domain models.
    if (user.IsCook)
        return RedirectToRoute(/*kitchen route*/);
    else
        return RedirectToRoute(/*dashboard*/);
}