Cheshire Cat
Cheshire Cat

Reputation: 1961

With ASP.NET MVC should I always check User IsAuthenticated in my Controller?

Should I always check the IsAuthenticated property of the user inside the actions on a controller, even if the action or the entire controller requires the user to login by the [Authorize] attribute?

Is it really necessary or it's only a good practice?

Example:

[Authorize]
public class MyEntityController : Controller
{
    public ActionResult Index()
    {
        if (WebSecurity.IsAuthenticated)
        {
            var result = from p in _db.MyEntity
                         where p.UserId.Equals(WebSecurity.CurrentUserId)
                         select new MyEntityViewModel
                             {
                                 Id = p.Id,
                                 Date = p.Date,
                                 Description = p.Description,
                                 Count = p.MyOtherEntity.Count(),
                                 Username = WebSecurity.CurrentUserName
                             };

            return View(result);
        }

        return View();
    }
}

Upvotes: 1

Views: 718

Answers (1)

Sergey Lazutkin
Sergey Lazutkin

Reputation: 121

It is not necessary. [Authorize] attribute checks if user is logged and redirects to login page if user is not logged automatically

Upvotes: 4

Related Questions