Do you use the Authorize attribute to secure actions or controllers?
Rules to Better MVC|f6113a94-ea9d-4c29-9f67-4770573c432d
v2.0
Posted at
3/03/2017 6:50 AM by
Tiago Araujo
Rule Intro
ASP.NET MVC provides the AuthorizeAttribute which ensures there is a logged in user before it will execute an action. You can also provide parameters to restrict actions or controllers to only be accessible to certain roles or users. This is a better solution than checking whether a logged-in user exists in code as the authorisation itself doesn’t need to be repeated.
Page Content
public ActionResult Delete(string tagName)
{
if (!Request.RequestContext.HttpContext.User.IsInRole("CanDeleteTags"))
{
return new System.Web.Mvc.HttpUnauthorizedResult();
}
// delete view
return View();
}
- Figure: Bad Example – Checking for an appropriate role in code leads to repetition
[Authorize(Roles = "CanDeleteTags")]
public ActionResult Delete(string tagName)
{
// ...delete tag
return View();
}
- Figure: Good Example – Using the Authorize attribute to check for appropriate roles
{31714273-DDD8-4D9A-8173-4601244DD866}
Do you feel this rule needs an update?