Broken Authorization in .NET
Vulnerable example #1
The following ASP.NET Core snippet shows a MVC controller that does not protect an administrative action.
public class AccountController : Controller {
public ActionResult AdminFunctionality() {
}
}
Simple authentication and authorization controls can be enforced by adding the [Authorize]
attribute either on the controller or on the action.
Vulnerable example #2
The following ASP.NET Core snippet shows an incorrect mix of [AllowAnonymous]
and [Authorize]
attributes, resulting in a non-protected action.
[AllowAnonymous]
public class AccountController : Controller {
[Authorize]
public ActionResult AdminFunctionality() {
}
public actionResult PublicFunctionality() {
}
}
[AllowAnonymous]
bypasses all authorization statements, hence the [Authorize]
attribute is ignored and does not protect the administrative functionality.
Prevention
Apply the recommended authentication and authorization mechanisms depending on the framework of choice.
ASP.NET Core
ASP.NET Core authorization provides different models; a simple, declarative role, and a rich policy-based model. At its simplest, applying the [Authorize]
attribute to a controller or action limits access to any authenticated user. Once the user is authorized, controllers expose the ControllerBase.HttpContext
that can be leveraged to fetch the current user details.
[Authorize]
public class AccountController : Controller
{
public ActionResult AdminFunctionality()
{
var userName = HttpContext.User.FindFirst(ClaimTypes.Name).Value
// Do something based on the current user details
}
}
The [Authorize]
attribute can limit access to users who are members of a specific role, e.g. Administrator
in the following example.
[Authorize(Roles = "Administrator")]
public class AccountController : Controller
{
}
If policies have been configured at startup, they can be applied using the Policy property on the same attribute, e.g. [Authorize(Policy = "RequireAdministratorRole")]
. More complex authorization strategies can be enforced by using claims-based and policy-based authorizations, or by defining custom authorization methods AuthorizationHandler
. See the references for further information.
References
MITRE - CWE 285 - Improper Authorization
OWASP Top 10 2021 - Broken Access Control
OWASP - Authorization Cheat Sheet
Microsoft - Simple authorization in ASP.NET Core
Microsoft - Role-based authorization in ASP.NET Core