SSW Foursquare

Do you use AuthorizeAttribute to secure actions or controllers?

Last updated by Brook Jeynes [SSW] 9 months ago.See history

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 authorization itself doesn’t need to be repeated.

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 AuthorizeAttribute to check for appropriate roles

We open source. Powered by GitHub