N. Sch
N. Sch

Reputation: 687

How To Use [Authorize] properly

I have two groups of users, one group of people are being hired, and one group of people are hiring.

I would like to restrict access to certain pages for each group of users, but when I use [Authorize] in the controller, it allows access to any signed in user without differentiating which group they are from?

   [HttpPost]
        public ActionResult Signin(string username, string password)
        {
            var mgr = new Cleaners.Models.UserManager(@"Data Source=.\sqlexpress;Initial Catalog='Cleaning Lady';Integrated Security=True");
            var user = mgr.GetUser(username, password);
            if (user == null)
            {
                return View(new UserViewModel { Name = username });
            }

            FormsAuthentication.SetAuthCookie(user.UserName, true);
            UserViewModel.IsAuthenticated = User.Identity.IsAuthenticated;
            return RedirectToAction("Private");
        }

        [Authorize]
        public ActionResult Private()
        {
            return View();

        }

Is there any way to restrict access to "private" to users that were verified through this controller?

Upvotes: 2

Views: 14207

Answers (1)

Alisson Reinaldo Silva
Alisson Reinaldo Silva

Reputation: 10695

I'm giving a simple example:

    [Authorize(Roles="Contractor")]
    public ActionResult Private()
    {
        return View();

    }

This will check whether the current user/identity has a Role named Contractor.

I'd suggest you to read this article to understand the basics of it.

Upvotes: 4

Related Questions