A common-case scenario during the development of an ASP.NET MVC web application is the need to restrict the access to some web resources to authenticated users only. If our application features an authentication system based on ASP.NET Membership framework (like the ASP.NET Membership Provider or the updated ASP.NET Identity) you can easily fullfill the task by using the AuthorizeAttribute provided in the System.Web.Mvc namespace to only allow specific Users and/or Roles for a whole Controller and/or for a specific ActionResult:
1 2 3 4 5 |
[Authorize(Roles = "Administrators, Operators")] public class HomeController : BaseController { ... } |
1 2 3 4 5 6 7 8 |
public class HomeController : BaseController { [Authorize(Roles = "Administrators, Operators")] public ActionResult Index() { ... } } |
This simple yet effective approach requires the user to authenticate himself using a login mechanism (usually a login form page or view) and that's why it's not really useful when you need to put togheter a RESTful interface and/or a WebService of any kind. The best way to deal with these things is to adopt one of the many authentication mechanisms supported by the HTTP protocol: Basic, Digest, NTLM just to mention some. The most used, yet also the easiest one to blend into a MVC pattern, it's definitely the Basic Authentication.
To implement it in your application just add the following ActionFilter custom attribute to your project:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class BasicAuthenticationAttribute : ActionFilterAttribute { public string BasicRealm { get; set; } protected string Username { get; set; } protected string Password { get; set; } public BasicAuthenticationAttribute(string username, string password) { this.Username = username; this.Password = password; } public override void OnActionExecuting(ActionExecutingContext filterContext) { var req = filterContext.HttpContext.Request; var auth = req.Headers["Authorization"]; if (!String.IsNullOrEmpty(auth)) { var cred = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(auth.Substring(6))).Split(':'); var user = new { Name = cred[0], Pass = cred[1] }; if (user.Name == Username && user.Pass == Password) return; } var res = filterContext.HttpContext.Response; res.StatusCode = 401; res.AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Ryadel")); res.End(); } } |
As you can see the filter checks for the presence of the Authorization request field and acts accordingly:
- If it's there, it checks the given username and password with those expected by the server application.
- If it's not there, it builds a standard 401 Http Response to tell the client that we need some credentials to access that specific resource. This kind of response will make most web browsers prompt the user with an "insert username and password" standard popup form.
The above implementation requires the developer to manually insert the username and password as ActionFilter required parameters but can be easily extended to make it support any authorization mechanism (MembershipProvider, ASP.NET Identity, custom userbase on an external DBMS or file, etc.) by removing the custom constructor and modifying the OnActionExecuting method IF block accordingly.
The BasicAuthenticationActionFilter attribute is just as versatile as the previously mentioned Authorize attribute, meaning that it can be used to put under Basic Authentication a whole controller or a specific ActionResult:
1 2 3 4 5 |
[BasicAuthenticationAttribute("your-username", "your-password", BasicRealm = "your-realm")] public class HomeController : BaseController { ... } |
1 2 3 4 5 6 7 8 |
public class HomeController : BaseController { [BasicAuthenticationAttribute("your-username", "your-password", BasicRealm = "your-realm")] public ActionResult Index() { ... } } |