Chapter 10. Adding Authentication and Authorization

In this chapter, I will demonstrate how to create your own Authentication and Authorization filters. There are many tutorials available on the Internet about setting up FormsAuthentication together with ASP.NET Membership to manage users in your application—in fact, this is a built-in option when you create a new MVC application with Visual Studio. To avoid reinventing the wheel, this chapter will implement Basic Access Authentication. Basic authentication allows a web browser to provide a username and password when performing a request against the web server. The authentication is provided in the HTTP Headers as a Base64-encoded string.

Authentication Overview

Authentication filters did not exist prior to MVC 5; instead, it was mixed together in a single Authorization filter. As of MVC 5, there is a nice and clear separation of concerns with authentication and authorization.

Creating a filter involves implementing two functions:

This function is called at the start of the life cycle and is responsible for validating the credentials, if supplied. This is described in more detail in the following text.
This function is called at the end of the life cycle for every request. It is responsible for requesting authentication when the request is unauthorized.

The role of the OnAuthentication function is three-fold (a flowchart is shown in Figure 10-1):

  1. If no authentication is provided, ...

Get ASP.NET MVC 5 with Bootstrap and Knockout.js now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.